PYTHON • CONTROL FLOW

For Loops — Use for loops to iterate over ranges, lists, and strings

Master the art of repeating actions automatically over sequences of data in Python.

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.

1801
Jacquard Loom
Joseph Marie Jacquard invented a loom that used punched cards to repeat weaving patterns automatically, foreshadowing the concept of programmed loops.
1950s
FORTRAN's DO Loop
IBM's FORTRAN language introduced the DO loop, one of the first high-level loop constructs. Programmers could now repeat calculations without rewriting code.
1972
C Language for Loop
The C programming language formalized the for loop with initialization, condition, and increment — a pattern still used in Java, JavaScript, and many other languages today.
1991
Python Is Created
Guido van Rossum released Python, which simplified the for loop into a clean, readable "for item in sequence" pattern — making iteration more intuitive than ever before.

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.

1

Iteration

The process of repeating a block of code once for each item in a sequence. Each repetition is called one iteration.
2

Loop Variable

A temporary variable that holds the current element from the sequence during each iteration. You choose its name, like i, item, or letter.
3

Sequence (Iterable)

Any object Python can step through one element at a time. Common iterables include range() objects, lists, and strings.
4

Loop Body

The indented block of code that runs once per iteration. Python uses indentation (typically 4 spaces) to define which lines belong to the loop body.
5

The range() Function

A built-in function that generates a sequence of integers. range(5) produces 0, 1, 2, 3, 4. It does not include the stop value.
✦ KEY TAKEAWAY
Think of a for loop like a conveyor belt at a factory. Each item on the belt is an element from your sequence. A worker (the loop body) performs the same action on every item as it passes by. When the belt is empty, the job is done. You don't need to count items or decide when to stop — the belt handles that automatically.

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.

The flowchart above shows the execution path of a for loop iterating over a list of three fruits. The loop checks if more items remain, assigns the next item to the variable 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.

FOR LOOP SYNTAX
for <variable> in <sequence>: <loop body>
variable — name you choose for the current item; sequence — any iterable (range, list, string); loop body — indented code that runs once per item.

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.

RANGE FUNCTION FORMS
range(stop) → 0, 1, 2, ..., stop−1 range(start, stop) → start, start+1, ..., stop−1 range(start, stop, step) → start, start+step, start+2×step, ...
The stop value is always excluded. If step is negative, the sequence counts downward.

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.

This side-by-side comparison shows for loops iterating over a 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.

Calculate the Average of Passing Scores
1
Step 1 — Define the Data and AccumulatorsWe start by creating our list of scores and initializing two accumulators: one for the running total and one for counting how many passing scores we find. scores = [88, 42, 95, 67, 73, 100, 55] passing_total = 0 passing_count = 0
passing_total = 0, passing_count = 0
2
Step 2 — Write the For Loop with a ConditionWe iterate over each score in the list. Inside the loop body, we check if the score is 70 or above. If it is, we add it to our total and increment the count. for score in scores: if score >= 70: passing_total += score passing_count += 1
After all iterations: passing_total = 356, passing_count = 4
3
Step 3 — Trace Through Key IterationsIteration 1: score = 88 → 88 ≥ 70, so total becomes 88, count becomes 1. Iteration 2: score = 42 → 42 < 70, skip. Iteration 3: score = 95 → total becomes 183, count becomes 2. Iteration 4: score = 67 → skip. Iteration 5: score = 73 → total becomes 256, count becomes 3. Iteration 6: score = 100 → total becomes 356, count becomes 4. Iteration 7: score = 55 → skip.
4
Step 4 — Calculate and Print the AverageAfter the loop, we divide the total by the count to get the average. We use the values accumulated during the loop. average = passing_total / passing_count print("Average passing score:", average)
average = 356 / 4 = 89.0
💡 Pro Tip
Tracing through each iteration by hand (as we did in Step 3) is a valuable debugging technique. When a loop isn't producing the output you expect, write down the value of every variable after each iteration — you'll often spot the bug immediately.

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.

Key differences between for loops and while loops in Python
FeatureFor LoopWhile Loop
When to useWhen you know the number of iterations or have a sequence to traverseWhen the number of iterations is unknown and depends on a condition
TerminationAutomatically ends when the sequence is exhaustedEnds when the condition becomes False (risk of infinite loop)
Loop variableAutomatically assigned from the sequenceMust be manually initialized and updated
Typical use caseProcessing each item in a list, counting with range()Repeating until user types 'quit', waiting for valid input
ReadabilityGenerally more readable and concise for sequence-based tasksCan be more flexible but requires careful management
✦ KEY TAKEAWAY
Think of it this way: a for loop is like taking a guided tour through a museum — you know exactly which rooms you'll visit and when the tour ends. A while loop is like exploring a maze — you keep going until you find the exit, but you don't know in advance how many turns that will take. For most beginner programs, if you have a collection of data, the for loop is the right choice.

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.

How the for loop connects to advanced Python concepts
What You Know NowWhat 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 listNested for loops: looping inside a loop to handle 2D data like grids or tables
Iterating over a list by elementenumerate() — get both the index and the element at the same time
Iterating over lists and stringsIterating over dictionaries, sets, file lines, and custom objects using the iterator protocol
Simple for loop bodybreak 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

PROBLEM 1 — CONCEPTUAL
What is the output of the following code? for i in range(3): print(i) Explain why the number 3 is not printed.
PROBLEM 2 — BASIC CALCULATION
Write a for loop that calculates the sum of all integers from 1 to 20 (inclusive) and prints the result. What value should the result be?
PROBLEM 3 — INTERMEDIATE
Given the string 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?
PROBLEM 4 — APPLIED
A teacher stores student grades in a list: 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.
PROBLEM 5 — CRITICAL THINKING
Write a for loop that takes the string 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.

Varsity Tutors • Python • For Loops — Use for loops to iterate over ranges, lists, and strings