Learn Python Programming  /  Control Flow  /  For Loop

For Loop

A for loop in Python iterates directly over the items of any sequence โ€” a list, string, range, or dictionary โ€” without needing an explicit counter.

Basic for Loop with range()

R Code
for i in range(1, 6):   # 1 up to (not including) 6
    print(i ** 2)
Output
1
4
9
16
25

Looping Directly Over a List

Unlike many languages, Python lets you loop over the actual items directly - no index needed unless you specifically want one.

R Code
fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print("I like", fruit)
Output
I like apple
I like banana
I like mango

Looping with an Index: enumerate()

R Code
fruits = ["apple", "banana", "mango"]

for i, fruit in enumerate(fruits):
    print(i, ":", fruit)
Output
0 : apple
1 : banana
2 : mango
💡 Tip
enumerate(fruits, start=1) lets you begin counting from 1 instead of 0, if that reads more naturally for your output.

Looping Over Two Lists Together: zip()

R Code
names = ["Rafi", "Meera", "Zayn"]
scores = [88, 92, 76]

for name, score in zip(names, scores):
    print(name, "scored", score)
Output
Rafi scored 88
Meera scored 92
Zayn scored 76

break and continue in a for Loop

R Code
for i in range(1, 11):
    if i % 2 == 0:
        continue   # skip even numbers
    if i > 7:
        break      # stop once i exceeds 7
    print(i)
Output
1
3
5
7

Advanced: Nested for Loops

🚀 Advanced Example
Nested loops work through every combination of two sequences - here, building a small multiplication table.
R Code
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}", end="   ")
    print()   # newline after each row
Output
1 x 1 = 1   1 x 2 = 2   1 x 3 = 3   
2 x 1 = 2   2 x 2 = 4   2 x 3 = 6   
3 x 1 = 3   3 x 2 = 6   3 x 3 = 9
💡 Tip
Before reaching for a for loop over a list, consider whether a list comprehension could do the same job in one, more readable line. Loops still shine when each step has side effects, like printing or writing to a file.

Key Points

  • for item in sequence loops directly over the items of a list, string, range, or dictionary.
  • enumerate() gives you the index alongside each item; zip() lets you loop over two lists in parallel.
  • break stops the loop entirely; continue skips to the next iteration.
  • Prefer a list comprehension over a for loop when you are just building a new list.