Lists and indexes
Think of a program that keeps a week of temperatures. With what you know now, it would need seven variables, monday to sunday, and a program that reads values until the user stops couldn't work at all, because it can't make up new variable names as it runs. A list solves both problems: it keeps any number of values under one name. You write it in square brackets, with commas between the values:
temperatures = [18, 21, 17, 25] # a list of four numbers
names = ["Ada", "Linus", "Grace"]
empty = []
print(temperatures)
print(names)
print(empty)
[18, 21, 17, 25]
['Ada', 'Linus', 'Grace']
[]The values in a list are its items (or elements). [] is an empty list, with no items yet. When you print a list, Python shows it the way you would write it in code, so strings in a list are shown with quotes, as in the interpreter.
Indexes
Each item has an index, its place in the list. As with the characters of a string, the first index is 0, and -1 is the last item:
temperatures = [18, 21, 17, 25]
print(temperatures[0])
print(temperatures[2])
print(temperatures[-1])
print("Change from first to last:", temperatures[-1] - temperatures[0])
18
17
25
Change from first to last: 7The function len gives the number of items, so the last index is len(temperatures) - 1. An index past the end stops the program:
temperatures = [18, 21, 17, 25]
print(len(temperatures))
print(temperatures[4])
4Traceback (most recent call last):
File "main.py", line 3, in <module>
print(temperatures[4])
~~~~~~~~~~~~^^^
IndexError: list index out of rangeThe list has 4 items, at indexes 0 to 3. Index 4 would be a fifth item, which doesn't exist.
Changing an item
Unlike a string, a list can be changed after it's made. Give an item a new value as you would give a variable one:
temperatures = [18, 21, 17, 25]
temperatures[2] = 19
temperatures[0] = temperatures[0] + 1
print(temperatures)
[19, 21, 19, 25]The other items stay as they were. An index in square brackets on the left of = says which item gets the new value.