Objects can be used as sequence indexes to access a specific element from the sequence, through the following syntax:
my_list = [1, 2, 3, 4]
x = 1
print(my_list[x]) # This will print 2
Whenever an object is used as a sequence index, the Python interpreter calls its __index__
method to compute the index that needs to
be accessed from the sequence.
Any object can be used as sequence index, as long as it defines an __index__
method that returns an int
. Most commonly,
sequence indexes are simply integers.
Similarly, sequences can be sliced through the following syntax:
my_list = [1, 2, 3, 4]
x = 1
print(my_list[1:3]) # This will print [2, 3]
If an invalid object is used as a sequence index, a TypeError
will be raised.