Why this matters
One variable holds one value. But programs often deal with many values at once: the days of the week, a row of test scores, a shopping basket. A list holds them all under a single name, and you reach each element by its position.
The idea
You declare a list with square brackets, separating items by commas:
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
number = [7, 22, 11, 34, 17]
Each element has an index, its position number. Indexes start at 0, not 1:
number = 7 22 11 34 17
index 0 1 2 3 4
So number[0] is 7 and number[3] is 34. Because you can use a variable as the index
(number[i]), lists pair perfectly with a for loop to process every element. Add a new
element to the end with .append(...):
a = []
a.append(1)
a.append(4)
print(a) # [1, 4]
Picture it
flowchart TD A([Start: a = empty list]) --> B[a.append 1] B --> C[a.append 4] C --> D[a.append 9] D --> E([print a -> 1, 4, 9])
Worked example
number = [7, 22, 11, 34, 17]
print(number[0]) # 7
print(number[4]) # 17
total = 0
for i in range(0, 5):
total = total + number[i]
print(total) # 91
Your turn
Predict what a list program prints, then write functions that read elements by index and
build lists with append.
Recap
- A list stores many values under one name, in order.
- The index starts at 0;
a[0]is the first element. .append(x)addsxto the end of the list.