Iterating with for Loops
Concepts covered: Iteration
A for loop repeats a block of code once for each item in a sequence. Without one, processing 50 files means writing 50 nearly identical blocks of code. A loop collapses all of that into 3 lines.
The for loop iterates over each item in a sequence (like a list, string, or tuple) one at a time. On each iteration, the loop variable is assigned the next item from the sequence, and the loop body executes with that value.
Basic for loop syntax
A for loop has the form: for variable in sequence: followed by an indented block. The variable takes on each value from the sequence in order:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
print("Done!")Output:
I like apple I like banana I like cherry Done!
The loop executes 3 times: fruit is "apple" on the first iteration, "banana" on the second and "cherry" on the third. Once all items are processed, the loop ends and execution continues with the next unindented statement.
Looping over strings
Strings are sequences of characters, so you can loop over them character by character:
word = "Python"
for char in word:
print(char)Output:
P y t h o n
Each character in the string becomes the loop variable in turn.
Accumulating results
To build up a result as you loop through items, initialize an accumulator before the loop and update it inside:
numbers = [10, 20, 30, 40, 50]
# Calculate the sum
total = 0
for num in numbers:
total = total + num
print("Sum:", total)
count = 0
for num in numbers:
if num > 25:
count = count + 1
print("Numbers > 25:", count)Output:
Sum: 150 Numbers > 25: 3
Building new lists
You can create new lists by looping through existing ones and appending transformed items:
names = ["alice", "bob", "charlie"]
# Create a list of uppercase names
upper_names = []
for name in names:
upper_names.append(name.upper())
print(upper_names)
# Filter a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens)Output:
['ALICE', 'BOB', 'CHARLIE'] [2, 4, 6, 8, 10]
This pattern of initializing an empty list before the loop and appending items inside is called the accumulator pattern for lists. It's one of the most common patterns in Python programming.
Test your understanding of the accumulator pattern. Choose the right operator in each blank to produce different results:
Looping over other data types
For loops work with any iterable object in Python. Beyond lists and strings, you can iterate over tuples, sets, dictionary keys, and more. The loop automatically handles extracting each element regardless of the underlying data structure:
# Looping over a tuple
coordinates = (10, 20, 30)
for coord in coordinates:
print("Coordinate:", coord)
print("---")
# Looping over a set (order may vary)
unique_items = {"apple", "banana", "cherry"}
for item in unique_items:
print("Item:", item)
print("---")
# Looping over dictionary keys
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
for name in scores:
print(name, "scored", scores[name])Output:
Coordinate: 10 Coordinate: 20 Coordinate: 30 --- Item: cherry Item: apple Item: banana --- Alice scored 95 Bob scored 87 Charlie scored 92
Finding values in lists
Combine a loop with a conditional to search for a specific value or for values that match a criterion:
# Find the first even number
numbers = [7, 3, 9, 4, 1, 8]
first_even = None
for num in numbers:
if num % 2 == 0:
first_even = num
break
print("First even:", first_even)
# Find the maximum value manually
values = [23, 67, 45, 89, 12, 56]
maximum = values[0]
for val in values:
if val > maximum:
maximum = val
print("Maximum:", maximum)
# Find all values above threshold
threshold = 50
above = []
for val in values:
if val > threshold:
above.append(val)
print("Above 50:", above)Output:
First even: 4 Maximum: 89 Above 50: [67, 89, 56]
About this lesson
This section is part of the Loops: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.