Name | [] (Index brackets) |
||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Examples |
# Create a list literal elements = ["H", "He", "Li", "B", "C", "N", "O"] # Retrieve a single list item 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 'N' # Assign a new value to an existing list element: elements[4] = 'Si' print(elements) # Prints ['H', 'He', 'Li', 'B', 'Si', 'N', 'O'] # 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. |
||||||||||||||
Syntax | [elem0, ..., elemN] sequence[index] sequence[index] = expr dict[key] dict[key] = value | ||||||||||||||
Parameters |
| ||||||||||||||
Related |
Slice {} (Curly braces) |
Updated on Tue Feb 27 14:07:12 2024.
If you see any errors or have comments, please let us know.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License