A variable holds one value. A list holds many, in order, inside square brackets with commas between: [3, 8, 5]. Lists can hold numbers, strings, anything, and they can grow and shrink while the program runs.
Each item has an index, starting at 0, just like the characters of a string. names[0] is the first item, names[-1] the last. You can also change an item by assigning to its index.
A slice takes a piece of a list: items[1:3] gives the items at indexes 1 and 2 (it stops before 3, like range). Leave a side out to go from the start or to the end. Slices work on strings too.
Lists have methods for changing them. append(x) adds x at the end, insert(i, x) puts x at index i, remove(x) takes out the first x, and pop() removes the last item and gives it back. Unlike string methods, these change the list itself. x in my_list asks whether x is in it.
basket = ["egg"]
basket.append("milk")
basket.append("bread")
basket.remove("egg")
last = basket.pop()
print(basket, last)
print("milk" in basket)
Prints
['milk'] bread
True
A for loop goes through a list item by item. Python also has built-in functions for the common jobs: sum(), max(), min() and sorted(), which gives back a sorted copy. my_list.sort() sorts the list itself instead.
temps = [18, 23, 15, 21]
for t in temps:
if t > 20:
print(t, "is warm")
print(sum(temps) / len(temps))
print(max(temps), sorted(temps))
Prints
23 is warm
21 is warm
19.25
23 [15, 18, 21, 23]
Asking for an index that doesn't exist (index 5 of a five-item list) stops with an IndexError.