Back

Activity 1.18: Intro to Lists

divider

Activity 1.18

Intro to Lists

Key Concepts

Lists

Indexing

The Problem With Separate Variables

Storing five related scores as five separate variables works — but what about 30 scores? Or 100?

score1 = 84
score2 = 91
score3 = 76
score4 = 88
score5 = 95

Lists: One Variable, Many Values

A list stores many related values under one variable name, in order, using square brackets.

scores = [84, 91, 76, 88, 95]

Accessing by Index

Each value in a list has a position called an index. Python is zero-based — the first value is at index 0, not 1.

scores = [84, 91, 76, 88, 95]
print(scores[0])
print(scores[2])

Accessing by Index

Terminal window
84
76

Updating an Element

Assigning to list[index] replaces the value already there.

scores = [84, 91, 76, 88, 95]
scores[1] = 100
print(scores)

Updating an Element

Terminal window
[84, 100, 76, 88, 95]

Today's Objectives

  • Creating a list with [ ]
  • Accessing elements by index, starting at 0
  • Updating an element by assigning to its index

Key Terms

List
A single variable that stores multiple values in order.
Element
One value stored inside a list.
Index
The position of an element in a list.
Zero-Based Indexing
The first element of a list is at index 0, not 1.

'F' → Fullscreen

divider

Build

Create a new Python program named 1-18-intro-to-lists.


Task 1: Create + Access

  • Create a list named foods with 5 favorite foods.
  • Print the first, third, and last foods, each with a label.
Intro to Lists
foods = ["pizza", "tacos", "sushi", "pasta", "burgers"]
print(f"First food: {foods[0]}")
print(f"Third food: {foods[2]}")
print(f"Last food: {foods[4]}")

Task 2: Update Elements

  • Update the first and last foods to new values.
  • Print the whole updated list.
Intro to Lists
foods = ["pizza", "tacos", "sushi", "pasta", "burgers"]
print(f"First food: {foods[0]}")
print(f"Third food: {foods[2]}")
print(f"Last food: {foods[4]}")
foods[0] = "ramen"
foods[4] = "waffles"
print(f"Updated foods: {foods}")
divider

Checkpoint

Verify your program works correctly.

Example Output
First food: pizza
Third food: sushi
Last food: burgers
Updated foods: ['ramen', 'tacos', 'sushi', 'pasta', 'waffles']
divider

Reflection

Answer the following questions before submitting your work.

  1. What is an index? What is an element?
  2. Why does the first food live at index 0 instead of index 1?
  3. If a list has 5 elements, what is the index of the last one?
divider

Submit

Submit the required files to the appropriate dropbox.

Activity Complete