Course contentsShow
← Python
Lesson 18 of 1,0601. Foundations and EnvironmentFree lesson

Iterating Over Sequences with For Loops

You will learn how to process collections of items one by one using a controlled loop structure to automate repetitive tasks.

In this lesson, you will learn how to use the for loop to process items in a sequence one by one, allowing you to automate repetitive tasks with precision.

The Power of the for Loop

So far, you have used while loops to repeat actions based on a condition. However, when you have a specific collection of items—like a list of names or a series of numbers—while loops can become cumbersome. A for loop is designed specifically to "iterate" over a sequence, meaning it automatically visits each item in that sequence in order, one at a time, without needing a manual counter.

How It Works

Think of a for loop like a teacher walking down a row of desks. The teacher (the loop) stops at each desk (the item), performs an action, and then moves to the next one automatically.

In Python, the syntax is clean and readable:

# A simple list of fruits
fruits = ["apple", "banana", "cherry"]

# The 'for' loop
for fruit in fruits:
    print("I love eating: " + fruit)

Breaking Down the Syntax

  1. for: This keyword starts the loop structure.
  2. fruit: This is a temporary variable name. You can name it whatever you like! During the first turn, it holds "apple". On the second turn, it becomes "banana", and so on.
  3. in: This keyword tells Python which sequence you want to traverse.
  4. fruits: This is the collection (the sequence) you are iterating over.
  5. The Indented Block: Every line indented under the for statement will run once for every item in your list. Once the sequence is exhausted, the loop stops automatically.

Unlike a while loop, where you have to manually update a counter to avoid an infinite loop, the for loop knows exactly when to stop because it follows the length of the sequence provided. This makes your code safer, cleaner, and much easier to read when you know exactly how many items you need to process.

Key Takeaway: A for loop simplifies repetitive tasks by automatically traversing a sequence, assigning each item to a temporary variable until every element has been processed.