Python for Loop

Learn Python for loop syntax with simple examples using lists, strings, range(), dictionaries, nested loops, break, continue, pass, and for else.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python for Loop

A for loop runs its body once for each item drawn from an iterable (list, string, tuple, dict keys, set, range, and more). The Python tutorial describes this as assigning each value to the loop variable in turn.

When you only need a single yes/no over items, any() / all() with a generator can replace a manual flag loop—see Python any() and all().

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Python for loop syntax

text
for item in iterable:
    # body (indented; colon required)

The header ends with a colon. The body must be indented consistently. item can be any name; iterable is any object that produces values when iterated.


Simple Python for loop example

python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
Output

You should see apple, banana, and cherry on separate lines. That is the pattern: each iteration assigns the next element to fruit, then runs the body.


Python for loop with list

Lists are the most common iterable. For more list operations, see Python list.

python
nums = [10, 20, 30]
total = 0
for n in nums:
    total += n
print(total)
Output

You should see 60.


Python for loop with string

A string iterates character by character.

python
for ch in "hi":
    print(ch)
Output

You should see h then i.


Python for loop with range()

In Python 3, range returns a range object, not a list. It yields integers one at a time in loops and avoids storing every number in memory. For start, stop, step, and reverse counting, see Python range(). The stop value is exclusive: range(3) yields 0, 1, 2.

python
for number in range(3):
    print(number)
Output

You should see 0, 1, 2. With two bounds, range(2, 5) starts at 2 and stops before 5.

python
for n in range(2, 5):
    print(n)
Output

You should see 2, 3, 4.


Python for loop with dictionary

Looping for key in my_dict walks keys. Use .items() when you need both key and value.

python
scores = {"Ada": 100, "Bob": 85}

for name in scores:
    print(name, scores[name])

for name, value in scores.items():
    print(name, value)
Output

Each pair of lines should list the same entries in insertion order. For dict basics, see Python dictionary example.


Python for loop with enumerate()

When you need an index and the value, use enumerate instead of range(len(...)) when it reads more clearly.

python
words = ["a", "bb"]

for i, w in enumerate(words):
    print(i, w)
Output

You should see 0 a then 1 bb. For more patterns, see Python enumerate().


Common iterables (quick table)

Iterable Typical loop
List for item in items:
String for char in text:
Tuple for item in values:
Dictionary for key in data: or for k, v in data.items():
Set for item in unique_values:
Range for number in range(5):

Nested for loop in Python

Each outer iteration runs the full inner loop. Here each inner value is squared correctly:

python
for i in range(2, 4):
    print(i, "squared is", i * i)
Output

You should see 2 squared is 4 then 3 squared is 9.

python
for i in range(1, 3):
    for j in range(1, 3):
        print(i, j, i * j)
Output

You should see four lines of small products (1 1 1 through 2 2 4).


Python for loop with break

break leaves the innermost for (or while) immediately.

python
for n in range(10):
    if n == 3:
        break
    print(n)
Output

You should see 0, 1, 2. For more control-flow detail, see Python break statement.


Python for loop with continue

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

python
for n in range(4):
    if n == 2:
        continue
    print(n)
Output

You should see 0, 1, 3. See also Python continue.


Python for loop with pass

pass is a no-op placeholder—useful when syntax requires a body but you have not written logic yet.

python
for n in range(2):
    pass

print("done")
Output

You should see done.


Python for loop with else

The else clause on a for loop runs after the loop completes all iterations without break. If break runs, the else block is skipped. This is different from if / else: think “else means no break occurred.”

python
for n in [1, 2, 3]:
    if n == 10:
        break
else:
    print("no break")

for n in [1, 2, 3]:
    if n == 2:
        break
else:
    pass  # not executed because break ran
Output

You should see only no break from the first loop; the second loop ends with break, so its else is skipped.


Common mistakes with Python for loops

  • Omitting the colon at the end of the for line (SyntaxError).
  • Inconsistent indentation inside the loop body (IndentationError or wrong logic).
  • Expecting range(1, 5) to include 5—the stop index is always excluded.
  • Using range(len(items)) everywhere when enumerate(items) would be clearer.
  • Modifying a list while iterating over that same list (skips or duplicates elements).
  • Mixing up break (exit loop), continue (next iteration), and pass (do nothing).
  • Treating for / else like if / else—remember else ties to break, not truthiness of the last value.
  • Writing for x in 3:—integers are not iterable (TypeError).

Python for loop quick reference table

Need Pattern
Walk a sequence for x in seq:
Index + value for i, x in enumerate(seq):
Count with range for i in range(n):
Dict keys for k in d:
Dict key/value for k, v in d.items():
Stop early break
Skip one iteration continue
Placeholder body pass
Run if no break for ...: ... else:

Summary

Python’s for item in iterable: runs the body once per element from any iterable. Use range when you need numeric progress (remember the exclusive stop), use .items() on dicts when you need values, and prefer enumerate when an index helps readability. break, continue, and pass control flow inside the loop; for / else runs only when the loop finishes without break. When the stop rule depends on a changing condition rather than a fixed sequence, a while loop may read more clearly; branch inside either loop with if / else.


References


Frequently Asked Questions

1. Does Python for loop use indexes like C for (i=0; i<n; i++)?

Usually you loop over the iterable directly; when you need an index and value together, use enumerate() instead of range(len(...)) unless you truly need only the index.

2. What does the else clause on a for loop do?

The else block runs after the loop completes all iterations normally; it is skipped if the loop exits with break (or the function returns, or an uncaught exception propagates out of the loop).

3. In Python 3, does range(5) build a list of five numbers?

No—range returns a lightweight range object that yields integers on demand; it behaves like a sequence in loops and membership tests without storing every value in a list.

4. Can I change a list while iterating over it?

You should not grow or shrink the same list you are iterating with a for loop over that list—indexes shift and elements can be skipped or revisited; iterate over a copy or collect changes first.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …