Syllabus Lesson 13 of 239 · Control Flow
Control Flow

for Loops and range()

A for loop walks through a sequence one item at a time. You do not manage a counter yourself, which makes it safer than while for known-size jobs. The loop variable takes each value in turn:

for fruit in ["apple", "pear", "plum"]:
    print(fruit)

That prints each fruit on its own line. To repeat a fixed number of times, pair for with range(). range(5) produces 0, 1, 2, 3, 4 (it starts at 0 and stops before the number):

for i in range(5):
    print(i)   # 0 1 2 3 4

You can give range a start and stop. range(1, 6) gives 1, 2, 3, 4, 5 (start included, stop excluded):

total = 0
for n in range(1, 6):
    total = total + n
print(total)   # 15

Because the loop variable changes for you and range is finite, a for loop always ends on its own. To iterate over the items and their positions, wrap with enumerate:

for index, fruit in enumerate(["apple", "pear"]):
    print(index, fruit)   # 0 apple, then 1 pear
Your turn

Define a function count_evens(numbers) that takes a list of integers and returns how many of them are even. Use a for loop over the list. Hint: a number is even when n % 2 == 0. For example count_evens([1, 2, 3, 4]) is 2.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output