Warmup

  • Assign a variable num with a value of your choosing.
  • Write an if statement that checks to see if the value is both even and greater than 20, and prints even and greater than 20 if so.

Lesson 3.1: Lists

Intro to Data Structures

What is a List?

  • A list is a collection of items stored in one variable
  • Lists can hold numbers, text, or both
  • Lists keep items in order

Example:

fruits = ["apple", "banana", "cherry"]

Why Use Lists?

  • Store multiple values together
  • Easy to organize related data
  • More efficient than creating many variables

Example:

student1 = "Alice"
student2 = "Bob"
student3 = "Charlie"
# vs.
students = ["Alice", "Bob", "Charlie"]

Creating Lists

  • Use square brackets []
  • Items separated by commas

Example:

numbers = [1, 2, 3, 4, 5]
mixed = ["cat", 3.14, True]

Question: Can a list hold different data types?

Accessing Items

  • Use index numbers
  • Index starts at 0

Example:

colors = ["red", "green", "blue"]
print(colors[0])   # red
print(colors[2])   # blue

Q: What will print(colors[1]) output?

Changing Items

  • Assign a new value using the index
pets = ["dog", "cat", "fish"]
pets[1] = "hamster"
print(pets)   # ["dog", "hamster", "fish"]

Adding Items

  • Use .append() to add at the end
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)   # [1, 2, 3, 4]

Q: What will happen if we run numbers.append(99)?

Removing Items

  • Use .remove(value) to delete by value
  • Use .pop(index) to delete by position
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)   # ["apple", "cherry"]

fruits.pop(0)
print(fruits)   # ["cherry"]

Practice Time

  1. Make a list with 5 of your favorite foods
  2. Print the 2nd and 4th items
  3. Change one item to something else
  4. Add one new item
  5. Remove one item

Key Takeaways

  • Lists hold multiple items in one variable
  • Index starts at 0
  • We can access, change, add, and remove items
  • Lists are flexible and powerful for organizing data