Python For Loops
The for loop goes through the items of a collection one by one: the characters of a string, the items of a list, the lines of a file, or a sequence of numbers made by range. For each item it runs the indented block with a variable set to that item. Most loops in Python are for loops.
Looping over a collection
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print("I like", fruit)
for letter in "Hi!":
print(letter)I like apple I like banana I like mango H i !
There is no counter to manage and no index to get wrong: the loop variable simply takes each value in turn.
Counting with range
range produces a sequence of numbers. range(5) gives 0 to 4; range(2, 6) gives 2 to 5; a third number is the step:
for i in range(5):
print(i, end=" ")
print()
for i in range(2, 6):
print(i, end=" ")
print()
for i in range(10, 0, -3):
print(i, end=" ")
print()
print(sum(range(1, 101)))0 1 2 3 4 2 3 4 5 10 7 4 1 5050
Like slices, range stops before its stop value. range(1, 101) therefore gives exactly the numbers 1 to 100.
enumerate and zip
When you need the position as well as the item, use enumerate. To walk through two lists side by side, use zip:
names = ["Asha", "Ravi", "Meera"]
marks = [91, 78, 85]
for place, name in enumerate(names, start=1):
print(place, name)
for name, mark in zip(names, marks):
print(f"{name}: {mark}")1 Asha 2 Ravi 3 Meera Asha: 91 Ravi: 78 Meera: 85
Nested loops
A loop inside a loop runs completely for each step of the outer loop. This prints a small multiplication table:
for row in range(1, 4):
for col in range(1, 5):
print(f"{row * col:3}", end="")
print()1 2 3 4 2 4 6 8 3 6 9 12
break and continue work in for loops exactly as in while loops, and a for loop can also have an else block that runs when the loop ends without break.
Practice exercises
- Print the squares of the numbers 1 to 10.
- Count the vowels in a sentence with a
forloop over its letters. - Print every third number from 0 to 30 with
range. - Print a triangle of stars: one star on the first line, two on the second, up to five.