Tutorial 9/15 DATA STRUCTURES

Python: Lists

Store multiple items in a single variable using Index positioning.

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.

Worked Example

In Python, we count starting from ZERO.

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

Updating Items

You can replace any item by targeting its position.

scores = [10, 20]
scores[0] = 99
# Update Index 0
print(scores)
# Prints [99, 20]
Active Recall

Predict Output

Targeting the middle item. What exactly prints?

nums = [10, 20, 30]
print(nums[1])
Level 22: Bronze

Food List

"Create a list of 3 foods. Update Index 1 to be 'Pizza' and print the whole list."

> bronze_stream_standby
Level 23: Silver

Out of Range!

"There are only 2 items in this list (Index 0 and 1). Fix the error to print the number 50."

> debugger_module_active
Level 24: Gold

Team Picker

Independent Construction Required

  • Create a list of 4 names (e.g. "A", "B", "C", "D").
  • Ask the user for a number between 0 and 3.
  • Convert to int().
  • Print the name at that index from the list.
> user_interface_standby