Accessing List Elements
Now that you can create a list, let's read its elements one by one.
Every element has its position in the list, called its index. Indexes are counted from zero: the first element has index 0, the second index 1, the third index 2, and so on. You can think of the index as the number of steps from the start of the list: the first element is right at the start, zero steps away.
resolutions = ["Keep a diary", "Take a falconry course", "Learn to juggle"]Here "Keep a diary" has index 0, "Take a falconry course" index 1 and "Learn to juggle" index 2.
To get an element, write the list's name and then the element's index in square brackets:
print(resolutions[0])
print(resolutions[2])This prints:
Keep a diary
Learn to juggleThe elements are printed without quotes: each of them is an ordinary text, not a list, and print() shows text as it is.
An element you read like this is an ordinary value, so you can also store it in a variable or put it in an f-string:
first_resolution = resolutions[0]
print(f"First: {first_resolution}")This prints:
First: Keep a diaryWatch out for the most common mistake with lists: because counting starts at 0, the last of three elements has index 2, not 3. There is no element at index 3, so asking for it stops the program:
resolutions = ["Keep a diary", "Take a falconry course", "Learn to juggle"]
print(resolutions[3])The program ends with this error:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
IndexError: list index out of rangeIndexError is an error with an index, and list index out of range means that the index is outside the list. When you see it, check the index: the last element's index is one less than the number of elements.
Instructions
Print the first colleague in the list colleagues: print(colleagues[0]).
Create a variable favorite_colleague and store one colleague of your choice in it. Read the name from the list by its index, for example colleagues[2].
Print it with a label: print("Favorite:", favorite_colleague). The output shows, for example, Favorite: Lucy.
Start programming for free
3/12