Iterating with for Loops

Concepts covered: Iteration

A loop runs the same block of code once for every item in a sequence. Greeting 3 friends takes 3 print statements. Greeting 3,000 customers takes a loop, and the loop is the same 2 lines either way, because the number of passes comes from the data and the code stays fixed.

The for loop names a variable, then a sequence. for fruit in fruits: reads as "for each fruit in fruits". On every pass, Python assigns the next item to fruit and runs the indented lines under the colon. When the sequence runs out, the loop is over.

A list is a sequence of values written between square brackets and separated by commas, such as ["apple", "banana", "cherry"]. It keeps its items in the order they were written, and a loop visits them in that order: first item first, last item last.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print("I like", fruit)

print("Done!")
I like apple
I like banana
I like cherry
Done!

The loop body is 1 line, and it runs 3 times. On the first pass fruit holds "apple", on the second "banana", on the third "cherry". After the third pass there is no fourth item, so Python moves to the first line at the loop's own indentation. "Done!" prints once, after the 3 greetings, because it sits outside the body.

Passfruit holdsLine printed
1"apple"I like apple
2"banana"I like banana
3"cherry"I like cherry
after the loop"cherry" (unchanged)Done!

Strings are sequences too

A string is a sequence of characters, so a for loop over a string hands you 1 character per pass. "Python" has 6 characters, so the body below runs 6 times and prints 6 lines of 1 letter each. The loop variable holds a fresh 1-character string on every pass, and the original string is untouched.

word = "Python"

for char in word:
    print(char)
P
y
t
h
o
n

Carrying a result across passes

Printing each item is the smallest thing a loop can do. More often the loop builds one answer out of many items: a total, a count, a largest value. The pattern has 3 parts: a variable created before the loop with a starting value, a line inside the loop that updates it, and a line after the loop that uses the finished result.

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)
Sum: 150
Numbers > 25: 3
Passnumtotal after the pass
11010
22030
33060
440100
550150

total = 0 before the loop matters. If that line sat inside the body, total would reset to 0 on every pass and the final answer would be 50, the last number alone. The second loop counts instead of sums: count goes up by 1 only on passes where the if is true, which happens for 30, 40 and 50, so it prints 3.

Practice: counting letters

Run the program below in your head before you reveal its output. The if inside the loop fires only on passes where the character is "a". "banana" has 6 characters, so the body runs 6 times, and count moves on 3 of those passes.

word = "banana"
count = 0
for letter in word:
    if letter == "a":
        count = count + 1
print("a appears", count, "times")

Output:

a appears 3 times

Where a print sits decides how often it runs. Indented under the for, it shows the accumulator after every pass, which is how you watch a running total grow. Back at the loop's own indentation, it runs once and shows only the finished value. The question below puts the print inside the body.

The print sits inside the loop body. What does this program print?

total = 0
for n in [2, 4, 6]:
    total = total + n
    print(total)

Writing an accumulator from scratch means filling 3 slots in the right places: the starting value on the line above the for, the list's name after in on the for line, and the loop variable's name inside the body, spelled exactly as the for line spells it. A sum starts from 0, since adding 0 changes nothing.

A misplaced starting line fails without an error message. Python runs it on every pass, so the accumulator restarts each time, and the value left at the end reflects only the final pass. When a count comes out smaller than the data says it should, check whether its starting assignment sits inside the body.

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.