Lists: Storing Many Values
Create lists, read items by index, add and remove items, loop through a list, and calculate totals, maximums and averages from your data.
Welcome back!
Step 1 of 14Learn
One name, many values
A music app doesn't create a separate variable for every song in your playlist. That would mean song1, song2, all the way to song347. Instead it stores them together in a list:
playlist = ["Sunrise", "Night Drive", "Echoes", "Gravity"]
scores = [88, 92, 75, 100]
empty = []A list is written with square brackets, with items separated by commas. Lists keep their items in order and can hold any type: strings, numbers, booleans, even other lists.
You read an item by its index, starting at 0, just like characters in a string:
print(playlist[0]) # Sunrise
print(playlist[3]) # Gravity
print(playlist[-1]) # Gravity (last item)
print(len(playlist)) # 4Unlike strings, lists can be changed after they're created:
playlist[1] = "Starlight"Now the second song is "Starlight". Asking for an index that doesn't exist, like playlist[4] in a 4-item list, raises an IndexError. The valid indexes always run from 0 to len(list) - 1.
Step 2 of 14Compare
The playlist and its indexes
| Aspect | Sunrise | Night Drive | Echoes | Gravity |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
| Negative index | -4 | -3 | -2 | -1 |
Step 3 of 14Practice · Choose one
levels = ["forest", "cave", "castle", "volcano", "sky"]. What is levels[2]?
Step 4 of 14Learn
Adding, removing and slicing
Lists grow and shrink with methods:
| Code | What it does |
|---|---|
team.append("Zoe") | adds "Zoe" to the end |
team.insert(0, "Ali") | inserts "Ali" at index 0, shifting the rest right |
team.remove("Zoe") | removes the first "Zoe" it finds |
team.pop() | removes and returns the last item |
"Ali" in team | True if "Ali" is in the list |
team.sort() | sorts the list in place, A to Z or smallest to largest |
A slice takes a piece of a list (or string) with [start:stop]. Like range, the stop index is excluded:
top = [100, 95, 90, 82, 77, 60]
print(top[0:3]) # [100, 95, 90]
print(top[:2]) # [100, 95] (start defaults to 0)
print(top[4:]) # [77, 60] (stop defaults to the end)A slice gives you a new list, so the original stays the same.
Watch out for sort(): it changes the list and returns nothing. Writing scores = scores.sort() replaces your list with None, Python's "no value" value. Just write scores.sort() on its own line, or use sorted(scores), which returns a new sorted list.
Step 5 of 14Practice · Diagram
One list, three changes
After which change does "Ben" move from index 0 to index 1?
Tap the shape that answers the question, then press Check.
- team = ["Ben", "Cy"]
- append("Zoe")
["Ben", "Cy", "Zoe"]
- insert(0, "Ali")
["Ali", "Ben", "Cy", "Zoe"]
- remove("Cy")
["Ali", "Ben", "Zoe"]
Step 6 of 14Practice · Work it out
How many items are in bag at the end?
``
bag = ["sword", "map"]
bag.append("potion")
bag.append("key")
bag.remove("map")
bag.insert(0, "shield")
print(len(bag))
``
Step 7 of 14Practice · Fill in the blanks
Fill in the blanks
nums = [10, 20, 30, 40, 50]. Complete the slice that gives [20, 30, 40]:
nums[:]
Step 8 of 14Learn
Looping through a list
The real power of lists comes from loops. A for loop visits every item, in order:
scores = [88, 92, 75, 100, 64]
total = 0
for s in scores:
total += s
average = total / len(scores)
print(f"Average: {average:.1f}") # Average: 83.8Python also has built-in functions that do common jobs in one step: sum(scores) is 419, max(scores) is 100, min(scores) is 64. So the average could be sum(scores) / len(scores). Writing the loop yourself is still worth knowing, because many problems need a custom rule that no built-in covers, such as counting passing scores:
passing = 0
for s in scores:
if s >= 70:
passing += 1
print(passing, "passed") # 4 passedYou can also build a list inside a loop. Start with an empty list and append to it:
evens = []
for n in range(2, 11, 2):
evens.append(n)
print(evens) # [2, 4, 6, 8, 10]Step 9 of 14Practice · Chart
scores = [88, 92, 75, 100, 64]
Which item would min(scores) return?
Tap the bar that answers the question, then press Check.
Step 10 of 14Practice · Match the pairs
temps = [18, 25, 21, 30, 16]. Match each expression to its value.
Tap an answer, then tap the place where it belongs (or drag it there).
- max(temps)
- min(temps)
- sum(temps)
- len(temps)
Step 11 of 14Practice · Code challenge · Python
Code challenge · Python
Complete passing_scores(scores) so it returns a new list with only the scores that are 70 or higher, in their original order.
For example, passing_scores([88, 64, 92, 70, 55]) returns [88, 92, 70]. An empty list gives an empty list.
The def line and the return are already written for you; you will learn exactly how they work in the Functions lesson. Fill in the middle.
passing_scores([88, 64, 92, 70, 55])passing_scores([100, 99])passing_scores([12, 69])passing_scores([])
Step 12 of 14Note
Step 13 of 14Practice · True or false
After nums = [3, 1, 2] and nums = nums.sort(), the variable nums holds [1, 2, 3].
Step 14 of 14Practice · What would you do?
What would you do?
You're tracking the kills per match in a game: kills = [3, 7, 2, 9, 4]. You want to print the best match. Which line is the simplest correct way?
Lesson complete!