Name

[] (Index brackets)

Examples
# Create a list literal
elements = ["H", "He", "Li", "B", "C", "N", "O", "F", "Ne"]

# Retrieve a single item from the list with a given index
print(elements[3]) # Prints 'B'

# Negative indexes can be used, and count from the end of the list.
print(elements[-2]) # Prints 'F'

# Assign a new value to an existing element of a list:
elements[4] = 'Si'
print(elements) # Prints ['H', 'He', 'Li', 'B', 'Si', 'N', 'O', 'F', 'Ne']


# You can use index brackets with strings as well, to access individual
# characters by index:
message = "Now is the winter of our discontent"
print(message[0]) # Prints 'N'
print(message[-1]) # Prints 't'
print(message[11]) # Prints 'w'


# Index brackets are used to retrieve the value for a given key from a
# dictionary
element_names = {'H': 'hydrogen', 'He': 'helium', 'Li': 'lithium'}
print(element_names['He']) # Prints 'helium'

# Overwrite the value of an element, or add a new key/value pair, by assigning
# to the key:
element_names['Be'] = 'beryllium'
print(element_names['Be']) # Prints 'beryllium'

Description
Syntax
	[elem0, ..., elemN]
	sequence[index]
	sequence[index] = expr
	dict[key]
	dict[key] = value
Parameters
elem0, ..., elemN
sequence
index
expr
dict
key
value
Related Slice
{} (Curly braces)
Updated on Wed Jan 18 17:32:21 2017.
Creative Commons License