Historical Context & Motivation
Imagine you need to print the names of every student in your class. You could write a separate print statement for each one, but what if there are 200 students? The idea of iteration — repeating a set of instructions automatically — is one of the oldest and most powerful ideas in computing. From the earliest mechanical looms to modern programming languages, the concept of looping has been essential to making machines truly useful.
Python's for loop was designed with a clear philosophy: code should be easy to read and write. Instead of managing counters and conditions manually, Python lets you say "for each item in this collection, do something." This raises a key question: how exactly does a for loop traverse different types of data, such as number ranges, lists, and strings? That's exactly what this lesson covers.
Core Principles & Definitions
Before writing for loops, you need to understand a few foundational concepts. A for loop in Python follows a simple pattern: it picks each element from a sequence (like a list, string, or range), assigns it to a loop variable, and runs the indented block of code — called the loop body — once for each element. When the sequence is exhausted, the loop ends and Python moves on to the next line of code.
Iteration
Loop Variable
i, item, or letter.Sequence (Iterable)
range() objects, lists, and strings.Loop Body
The range() Function
range(5) produces 0, 1, 2, 3, 4. It does not include the stop value.Visual Explanation
The following diagram shows the flow of a Python for loop as it iterates over a list. Notice how the loop variable is updated before each execution of the loop body, and how control returns to the top of the loop until the sequence is exhausted.
fruit, runs the loop body, and then loops back to check for more items. When the list is exhausted, execution continues after the loop.Notice the diamond-shaped decision box in the middle. This is the key to understanding why for loops are so convenient: Python automatically tracks which item comes next and stops when the sequence is empty. You never have to write code to check whether the loop should continue — Python handles that behind the scenes.
How For Loops Work in Detail
Basic Syntax
Every for loop in Python follows the same general structure. You write the keyword for, then a loop variable name, then the keyword in, then the sequence to iterate over, and finally a colon. The indented lines below form the loop body.
Iterating Over range()
The range() function generates a sequence of integers. It can accept one, two, or three arguments. With one argument, range(n) produces integers from 0 up to (but not including) n. With two arguments, range(start, stop) begins at start and ends before stop. With three arguments, range(start, stop, step) adds a custom increment between values.
Iterating Over Lists
A list is an ordered collection of items enclosed in square brackets. When you iterate over a list, the loop variable takes on each element in order. Lists can contain any data type — integers, floats, strings, or even other lists. For example, for score in [90, 85, 78, 92]: would assign 90 to score in the first iteration, 85 in the second, and so on.
Iterating Over Strings
In Python, a string is a sequence of individual characters. When you use a for loop on a string, the loop variable receives one character at a time. For instance, for ch in "Hello": would iterate five times, with ch taking the values 'H', 'e', 'l', 'l', 'o'. This is incredibly useful for tasks like counting specific characters, reversing text, or validating user input.
Common For Loop Patterns
Now that you understand the three main sequence types, let's look at the most common patterns you'll use for loops in. These patterns show up again and again in real programs, so mastering them early will give you a strong foundation.
range (left, violet), a list (center, emerald), and a string (right, amber). Despite using different data types, the syntax is nearly identical.Accumulator Pattern
One of the most useful patterns is the accumulator pattern. You create a variable before the loop (set to zero or an empty string), then update it inside the loop body on each iteration. For example, to find the sum of numbers 1 through 10, you initialize total = 0 before the loop, and then inside the loop body write total = total + i (or equivalently total += i). After the loop finishes, total holds 55.
Counting Pattern
The counting pattern is similar to the accumulator, but you increment a counter by 1 each time a condition is met. For instance, to count how many vowels appear in a string, you set count = 0 before the loop, iterate over each character, and add 1 to count whenever the character is a vowel using an if statement inside the loop.
Worked Example
Let's walk through a complete example that combines several concepts: iterating over a list, using an accumulator, and using a conditional inside the loop. Our goal is to calculate the average of all passing scores (70 or above) from a list of test scores.
scores = [88, 42, 95, 67, 73, 100, 55]
passing_total = 0
passing_count = 0for score in scores:
if score >= 70:
passing_total += score
passing_count += 1average = passing_total / passing_count
print("Average passing score:", average)For Loops vs. While Loops
Python has two main loop types: for loops and while loops. While both repeat code, they serve different purposes. Understanding when to use each one is an important skill. The table below highlights their key differences.
| Feature | For Loop | While Loop |
|---|---|---|
| When to use | When you know the number of iterations or have a sequence to traverse | When the number of iterations is unknown and depends on a condition |
| Termination | Automatically ends when the sequence is exhausted | Ends when the condition becomes False (risk of infinite loop) |
| Loop variable | Automatically assigned from the sequence | Must be manually initialized and updated |
| Typical use case | Processing each item in a list, counting with range() | Repeating until user types 'quit', waiting for valid input |
| Readability | Generally more readable and concise for sequence-based tasks | Can be more flexible but requires careful management |
Connection to Advanced Concepts
The for loop you've learned in this lesson is the foundation for many advanced Python features. As you grow as a programmer, you'll encounter tools that build directly on this concept. Here's a preview of what lies ahead.
| What You Know Now | What Comes Next |
|---|---|
for item in list: | List comprehensions: [x**2 for x in range(10)] — build new lists in a single line |
| Iterating over one list | Nested for loops: looping inside a loop to handle 2D data like grids or tables |
| Iterating over a list by element | enumerate() — get both the index and the element at the same time |
| Iterating over lists and strings | Iterating over dictionaries, sets, file lines, and custom objects using the iterator protocol |
| Simple for loop body | break and continue — control flow within loops to skip iterations or exit early |
Every one of these advanced tools uses the same for ... in ... pattern you've learned today. Mastering the basics of iteration now means these future topics will feel like natural extensions rather than entirely new ideas. The ability to loop through data efficiently is at the heart of nearly every Python program you'll ever write.
Practice Problems
for i in range(3):
print(i)
Explain why the number 3 is not printed.message = "Programming is awesome!", write a for loop that counts how many lowercase vowels (a, e, i, o, u) appear in the string. What count do you get?grades = [92, 78, 65, 88, 55, 97, 70, 82]. Write a program using a for loop that creates two new lists: one for students who scored 70 or above (passing) and one for those who scored below 70 (failing). Print both lists.word = "racecar" and builds a new string that is the reverse of word. Then, use an if statement to check whether the word is a palindrome (reads the same forwards and backwards). Explain why this approach works and discuss whether there might be a simpler way to reverse a string in Python.Lesson Summary
Python's for loop uses the for variable in sequence syntax to iterate over any iterable object. The three most common iterables are range() for generating integer sequences (remembering the stop value is excluded), lists for stepping through collections of data, and strings for processing text one character at a time. The loop variable is automatically updated with each element, and the indented loop body executes once per iteration.
Key patterns include the accumulator pattern (building up a total or new string) and the counting pattern (tallying items that meet a condition). For loops are preferred over while loops when you know the sequence in advance, because they're safer (no infinite loops) and more readable. Mastering for loops prepares you for advanced concepts like list comprehensions, nested loops, and the enumerate() function.