[] (Index brackets)

# 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 Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

For lists and other mutable sequences (but not strings), you can overwrite a value at a particular index using the assignment operator (=).

Negative numbers inside of index brackets cause Python to start counting from the end of the sequence, instead of from the beginning. For example, the expression x[-1] evaluates to the last item of list x, x[-2] evaluates to the second-to-last item of list x, and so forth.

Finally, index brackets are used to retrieve or set the value for a given key in a dictionary. For example, the expression x[a] evaluates to whatever the value for key a is in dictionary x. The statement x[a] = b will set the value for key a in dictionary x to a new value b (overwriting any existing value).

Specifying an index beyond the bounds of the sequence raises an IndexError exception. Attempting to retrieve the value for a key that does not exist in a dictionary raises a KeyError exception.

	[elem0, ..., elemN]
	sequence[index] = expr
	dict[key] = value
elem0, ..., elemNlist of elements, separated by commas, used to initialize a list
sequencea list, string or other sequence
indexan integer index
expran expression, the result of which will be assigned to the given index in the sequence
dicta dictionary
keythe key whose value you want to retrieve
valuea new value for the given key
Related Slice
{} (Curly braces)
Updated on Tue Jul 11 06:52:23 2017.
Creative Commons License