The subscription syntax is usually used for selecting an element from a container – for example, to get a value from a dict:
>>> digits_by_name = {'one': 1, 'two': 2}>>> digits_by_name['two'] # Subscripting a dictionary using the key 'two'2
In the subscription syntax, the object being subscribed – a primary – is followed by a subscript in square brackets. In the simplest case, the subscript is a single expression.
Depending on the type of the object being subscribed, the subscript is sometimes called a key (for mappings), index (for sequences), or type argument (for generic types). Syntactically, these are all equivalent:
>>> colors = ['red', 'blue', 'green', 'black']>>> colors[3] # Subscripting a list using the index 3'black'>>> list[str] # Parameterizing the list type using the type argument strlist[str]
At runtime, the interpreter will evaluate the primary and the subscript, and call the primary’s __getitem__() or __class_getitem__() special method with the subscript as argument. For more details on which of these methods is called, see class_getitem versus getitem.
To show how subscription works, we can define a custom object that implements __getitem__() and prints out the value of the subscript:
See __getitem__() documentation for how built-in types handle subscription.
Subscriptions may also be used as targets in assignment or deletion statements. In these cases, the interpreter will call the subscripted object’s __setitem__() or __delitem__() special method, respectively, instead of __getitem__().
>>> colors = ['red', 'blue', 'green', 'black']>>> colors[3] = 'white' # Setting item at index>>> colors['red', 'blue', 'green', 'white']>>> del colors[3] # Deleting item at index 3>>> colors['red', 'blue', 'green']
All advanced forms of subscript documented in the following sections are also usable for assignment and deletion.