W3docs

Python For Loops

Learn how Python for loops work: syntax, range(), enumerate(), break, continue, else, nested loops, and iterating over lists, strings, and dicts.

A for loop in Python iterates over every item in a sequence — a list, tuple, string, dictionary, set, or any other iterable — and executes a block of code once per item. Unlike languages where for typically counts numbers, Python's for is a for-each loop that walks through items directly.

This chapter covers:

  • Basic syntax and how the loop variable works
  • The range() function for counted loops
  • break, continue, and the else clause
  • enumerate() and zip() for richer iteration
  • Iterating over strings, dictionaries, and nested structures
  • Nested for loops
  • The pass statement as a placeholder

Basic syntax

for variable in iterable:
    # block executed once per item

variable is assigned each successive item from iterable. The indented block runs once for every item.

Iterating over a list

python— editable, runs on the server

Output:

apple
banana
cherry

The loop assigns "apple" to fruit, runs print(fruit), then moves on to "banana", and so on until all items are exhausted.

Iterating over a string

A string is itself an iterable — each character is an item:

for ch in "Python":
    print(ch)

Output:

P
y
t
h
o
n

The range() function

range() generates a sequence of integers on demand. It is the most common way to run a loop a specific number of times.

range(stop)
range(start, stop)
range(start, stop, step)
ParameterDefaultMeaning
start0First value (inclusive)
stoprequiredUpper bound (exclusive)
step1Increment between values

Counting from 1 to 5

python— editable, runs on the server

Output:

1
2
3
4
5

range(1, 6) produces 1, 2, 3, 4, 5 — the stop value 6 is not included.

Counting in steps

for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

Counting backwards

A negative step iterates in reverse:

for i in range(10, 0, -2):
    print(i)

Output:

10
8
6
4
2

The break statement

break exits the loop immediately, before all items have been visited.

for i in range(1, 6):
    if i == 3:
        break
    print(i)

Output:

1
2

Once i equals 3, break fires and the loop stops — 3, 4, and 5 are never printed.

When to use break: searching a list and stopping as soon as you find a match; exiting early from a long computation.


The continue statement

continue skips the rest of the current iteration and moves straight to the next item.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

When i equals 3, continue skips print(i) and jumps to i = 4.


The else clause

Python's for loop supports an optional else block that runs only if the loop completed normally (i.e., was not terminated by break).

for i in range(1, 4):
    print(i)
else:
    print("Loop finished")

Output:

1
2
3
Loop finished

If the loop exits via break, the else block is skipped:

for i in range(1, 6):
    if i == 3:
        break
    print(i)
else:
    print("Loop finished without break")

Output:

1
2

The else clause is useful for signalling whether a search succeeded — if you break on a match, the else block only runs when no match was found.


enumerate() — loop with index and value

enumerate() pairs each item with its position index, so you get both in one loop without a separate counter variable.

colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(index, color)

Output:

0 red
1 green
2 blue

To start counting from a different number, pass start:

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)

Output:

1 apple
2 banana
3 cherry

zip() — loop over two sequences at once

zip() pairs items from two (or more) iterables side by side:

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
    print(name, score)

Output:

Alice 95
Bob 87
Charlie 92

zip() stops when the shortest iterable is exhausted.


Iterating over dictionaries

Iterating over a dictionary by default yields its keys:

person = {"name": "Alice", "age": 30, "city": "Paris"}
for key in person:
    print(key, ":", person[key])

Output:

name : Alice
age : 30
city : Paris

Use .items() to get key-value pairs together:

for key, value in person.items():
    print(key, ":", value)

Output:

name : Alice
age : 30
city : Paris

See also the Loop Dictionaries chapter for more patterns.


Nested for loops

A for loop can be placed inside another for loop. The inner loop runs fully for every single iteration of the outer loop.

python— editable, runs on the server

Output:

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

Gotcha: break inside a nested loop only exits the inner loop, not both. To exit both loops at once you need a flag variable or to refactor into a function and use return.


The pass statement

pass is a no-op placeholder. Use it when a for loop is syntactically required but you have nothing to put in the body yet:

for i in range(3):
    pass  # TODO: implement later

Without pass, Python would raise an IndentationError because an empty block is invalid syntax.


For loops vs list comprehensions

A common pattern is building a new list inside a for loop:

squares = []
for x in range(1, 6):
    squares.append(x ** 2)
print(squares)

Output: [1, 4, 9, 16, 25]

Python offers a more concise alternative called a list comprehension:

squares = [x ** 2 for x in range(1, 6)]
print(squares)

Output: [1, 4, 9, 16, 25]

List comprehensions are idiomatic for simple transformations; use a regular for loop when the body is complex or has side effects.


Choosing between for and while

SituationPrefer
You know the number of iterations or have an iterablefor
You loop until a condition changeswhile
You need index and valuefor + enumerate()
You loop over two lists togetherfor + zip()

Practice

Practice
Which built-in function generates a sequence of integers for use in a for loop?
Which built-in function generates a sequence of integers for use in a for loop?
Practice
What does the else clause of a for loop do?
What does the else clause of a for loop do?
Practice
What are the primary uses of for loops in Python?
What are the primary uses of for loops in Python?
Was this page helpful?