- Explain why loops are essential for working with lists.
- Use a
forloop to iterate through each item in a list. - Write a program that processes each item in a list (e.g., printing or modifying).
Processing Every Item in a List
Accessing one item at a time with an index is great, but the real power of lists is the ability to perform an action on every single item in the collection automatically. For this, we combine lists with a tool you already know: the for loop.
The for...in Loop: Simple and Elegant
Python provides a very clean and readable way to loop through a list. The syntax is like plain English: "For each item in my list, do this action."
my_list = ["apple", "banana", "cherry"]
The variable 'fruit' will hold "apple" on the first loop,
then "banana" on the second, and "cherry" on the third.
for fruit in my_list:
This indented block will run once for each item in the list.
print(f"I am thinking about a .")
Notice that you don't have to worry about indexes or range(). The for loop automatically handles getting each item for you one by one. This is the preferred way to access every item in a list.
Knowledge Check: Predict the Output
Let's see if you can predict the output of a simple loop. Complete the interactive exercise below.
Live Example: A Team Roster
The Trinket below demonstrates how to use a for loop to print a welcome message for every player on a team. It also shows how you can nest an if statement inside to do something special for a specific player. Run it, then try the challenges!
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.