Warmup

  • Store in my_list a list of 5 items
  • Store in partial_list a slice of my_list beginning at index 2 and stopping at index 4

Agenda

  • Tomorow's Class is in Belk Gym

  • Thursday class:

    • 3rd Block: Meet at Cone courtyard at 10:15
    • 4th Block: Meet at Cone courtyard at 12:20
    • We will walk together to Denny/Burson
  • Mr. Lapinel absent tomorrow (Lesson 3.4 is on your own)

  • Lesson 3.3 today

Due dates

  • Python Essentials 1 Module 3 Quiz due Thursday
  • Python Essentials 1 Module 3 Test due Friday
  • Unit 3 Quiz 1 Friday (lists, tuples, dictionaries)

Lesson 3.3 – Lists: Iteration

What we’ll learn today

  • How to loop through lists with for
  • How to use in with lists
  • Practical exercises combining loops + lists

Quick Review

  • What is a list slice?
  • Name two list methods from last class.

Looping Through Lists

  • We can use a for loop to go through each element.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Try It

  • Make a list of 5 animals.
  • Write a for loop to print each one.

Using Indexes

  • Sometimes you need the index too.
nums = [10, 20, 30]
for i in range(len(nums)):
    print(i, nums[i])

Class Question

  • When would it be useful to loop by index instead of by value?

Membership Test with in

  • Check if something is in the list.
colors = ["red", "green", "blue"]
if "red" in colors:
    print("Yes, red is here!")

Mini Practice

pets = ["dog", "cat", "fish"]
if "hamster" not in pets:
    print("Hamster not found")
  • What will it print?

Loop + Condition

  • We can mix loops with if-statements.
nums = [1, 2, 3, 4, 5]
for n in nums:
    if n % 2 == 0:
        print(n, "is even")

Mini Challenge

  1. Make a list of numbers from 1 to 10.
  2. Loop through them.
  3. Print only the odd numbers.