Python For Loops

A Python for loop goes through the items of a sequence, such as a list, string, tuple, dictionary or range, one at a time. Unlike for loops in C or Java, you do not manage a counter yourself; Python hands you each item directly.

Loop Through a List or String

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

for fruit in fruits:
    print(fruit.title())

for letter in "Hey":
    print(letter)
Apple
Mango
Cherry
H
e
y

The range() Function

range() produces a sequence of numbers. range(5) gives 0 to 4, range(2, 6) gives 2 to 5, and a third argument sets the step. The end number is never included.

print(list(range(5)))
print(list(range(2, 6)))
print(list(range(10, 0, -3)))

total = 0
for n in range(1, 101):
    total += n
print(total)
[0, 1, 2, 3, 4]
[2, 3, 4, 5]
[10, 7, 4, 1]
5050

Loop with Index: enumerate()

When you need both the position and the item, use enumerate() instead of range(len(...)). It is cleaner and less error-prone.

steps = ["Wash", "Chop", "Cook"]

for number, step in enumerate(steps, start=1):
    print(f"Step {number}: {step}")
Step 1: Wash
Step 2: Chop
Step 3: Cook

Loop Over Two Lists: zip()

zip() pairs up items from several lists so you can loop over them together. It stops at the shortest list.

names = ["Ali", "Sara", "John"]
scores = [88, 92, 79]

for name, score in zip(names, scores):
    print(name, score)
Ali 88
Sara 92
John 79

Nested Loops

A loop inside a loop runs the inner loop completely for every pass of the outer loop. This small multiplication table uses an f-string to align the numbers.

for row in range(1, 4):
    line = ""
    for col in range(1, 4):
        line += f"{row * col:4}"
    print(line)
   1   2   3
   2   4   6
   3   6   9

break, continue and else

They work exactly as in while loops. The else block runs only if the loop finished without hitting break.

for n in [7, 11, 9, 13]:
    if n % 3 == 0:
        print("Divisible by 3:", n)
        break
else:
    print("None divisible by 3")

for n in range(6):
    if n == 2:
        continue
    print(n, end=" ")
Divisible by 3: 9
0 1 3 4 5 

For Loop Tips

  • Do not add or remove items from a list while looping over it; loop over a copy instead
  • Use for key, value in my_dict.items() for dictionaries
  • Use _ as the loop variable when you do not need it: for _ in range(3)
  • Simple loops that build a list can often become a list comprehension

Frequently asked questions

How do I get the index in a Python for loop?

Use enumerate(): for i, item in enumerate(my_list):. Pass start=1 if you want counting to begin at 1.

Does range() include the last number?

No. range(1, 5) produces 1, 2, 3 and 4. Use range(1, 6) to include 5.

How do I loop backwards in Python?

Use reversed(my_list) or range with a negative step, for example range(10, 0, -1).

How do I loop through two lists at once in Python?

Use zip(list1, list2), which yields pairs of items. Use itertools.zip_longest if the lists have different lengths and you need every item.