In this lesson, you’ll see how to access individual elements and sequences of objects within your lists. Lists elements can be accessed using a numerical index in square brackets:
>>> mylist[m]
This is the same technique that is used to access individual characters in a string. List indexing is also zero-based:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0]
'spam'
>>> a[2]
'bacon'
>>> a[5]
'lobster'
>>> a[len(a)-1]
'lobster'
>>> a[6]
Traceback (most recent call last):
File "<input>", line 1, in <module>
a[6]
IndexError: list index out of range
List elements can also be accessed using a negative list index, which counts from the end of the list:
JVargas on Dec. 13, 2019
Nice!