Card 9: Lists

Module 4: Data Structures

1 The Hook

Imagine you are going shopping. You buy apples, bananas, and milk.

Do you want 3 separate pockets (variables) to carry them?
Or ONE bag (List) to hold them all?

A List allows us to store many items in a single variable.

2 Worked Example

We count starting from ZERO.

friends = ["Sam", "Alex", "Jo"]
Index 0
"Sam"
Index 1
"Alex"
Index 2
"Jo"
print(friends[0]) # Prints "Sam"
print(friends[2]) # Prints "Jo"

Changing Items

You can update a list item just like a normal variable.

scores = [10, 20]
scores[0] = 99 # Change item at Index 0 to 99
print(scores) # Prints [99, 20]

PREDICT

What prints out?

nums = [10, 20, 30]
print(nums[1])

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Food List

1. Create the list with 3 foods.
2. Update Index 1 to be "Pizza".
3. Print the whole list.

> _
SILVER (FIX)

🥈 Out of Range!

There are only 2 items in this list (Index 0 and 1).
But we are trying to print Index 2.
Fix the code to print "50".

> _
GOLD (MAKE)

🥇 Team Picker

1. Create a list of 4 names.
2. Ask the user for a number (0-3).
3. Print the name at that index.

> _