Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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)
Output
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)))
Output
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}")
Output
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()
Output
  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

  1. Print the squares of the numbers 1 to 10.
  2. Count the vowels in a sentence with a for loop over its letters.
  3. Print every third number from 0 to 30 with range.
  4. Print a triangle of stars: one star on the first line, two on the second, up to five.