Python for loop
last modified November 18, 2026 Python 3.15
In this article we show how to create loops in Python with the
for statement.
A loop is a sequence of instructions that is repeated until a
certain condition is reached. For instance, we have a collection of items
and we create a loop to go through all elements of the collection. Loops in
Python are created with the for and while
statements.
The for statement
The Python for statement iterates over the items of any
iterable object, such as a string, list, tuple, dictionary, set, file, or
generator, in the order the iterable produces them.
for target in iterable:
statements
else:
statements
In each cycle, the next item is assigned to the target variable and the
body is executed. The loop ends when the iterable is exhausted. The optional
else clause is covered later. Unlike in C or Java, there is no
counter-based form; counting loops use range.
Looping over a string
A string is a sequence of characters, so a for loop goes
through it character by character.
word = 'cloud'
for letter in word:
print(letter)
We print the letters of the word one per line.
$ python loop_string.py c l o u d
Looping over lists and tuples
Lists and tuples are traversed from the first element to the last.
nums = (1, 2, 3, 4, 5, 6)
words = ['cup', 'star', 'monkey', 'bottle']
for n in nums:
print(n, end=' ')
print()
for word in words:
print(word.upper(), len(word))
print(f'last word: {word}')
The example prints the elements of a tuple on one line and the words of a list together with their lengths.
print(n, end=' ')
The end parameter replaces the default newline with a space, so
the numbers end up on one line.
print(f'last word: {word}')
A for loop does not create a new scope. After the loop, the
target variable keeps the last assigned value.
$ python loop_list_tuple.py 1 2 3 4 5 6 CUP 3 STAR 4 MONKEY 6 BOTTLE 6 last word: bottle
Repeating a block with range
The built-in range type represents an immutable sequence of
integers. range(stop) produces 0 to stop - 1;
range(start, stop) starts at start. Combined with
for, it repeats a block a given number of times.
for i in range(1, 6):
print(f'Statement executed {i}')
for _ in range(3):
print('hello')
The first loop runs five times and uses the counter in the message.
for _ in range(3):
print('hello')
When the counter is not needed, the underscore is used as the variable name by convention.
$ python repeat.py Statement executed 1 Statement executed 2 Statement executed 3 Statement executed 4 Statement executed 5 hello hello hello
Range with a step
The third argument of range is the step. It can be negative to
count down. The stop value is never included.
for n in range(1, 11):
print(n, end=' ')
print()
for n in range(0, 11, 2):
print(n, end=' ')
print()
for n in range(10, 0, -3):
print(n, end=' ')
print()
r = range(0, 1_000_000_000, 7)
print(r, len(r), r[3], 21 in r)
We generate three sequences of integers and inspect a large range.
r = range(0, 1_000_000_000, 7) print(r, len(r), r[3], 21 in r)
A range does not store its numbers; it computes them on demand.
Even a range with over a hundred million items takes a small, fixed amount
of memory and
supports len, indexing, and fast membership tests.
$ python ranges.py 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10 10 7 4 1 range(0, 1000000000, 7) 142857143 21 True
Looping with an index
When we need the position of an element as well, we use the
enumerate function. It yields pairs of an index and an
element.
words = ['cup', 'star', 'monkey', 'bottle', 'paper', 'door']
for idx, word in enumerate(words):
print(f'{idx}: {word}')
print('---')
for nr, word in enumerate(words[:3], start=1):
print(f'{nr}. {word}')
We print each word with its index. In the second loop, the
start parameter makes the numbering start at 1.
$ python loop_index.py 0: cup 1: star 2: monkey 3: bottle 4: paper 5: door --- 1. cup 2. star 3. monkey
Looping over a dictionary
Iterating over a dictionary yields its keys. The items,
keys, and values methods return views for
iterating over pairs, keys, or values. Dictionaries keep insertion order,
so the loop goes through the entries in the order they were added.
data = {'de': 'Germany', 'sk': 'Slovakia', 'hu': 'Hungary', 'cz': 'Czechia'}
for k in data:
print(k, end=' ')
print()
for k, v in data.items():
print(f'{k} is an abbreviation for {v}')
for v in sorted(data.values()):
print(v, end=' ')
print()
We print the keys, the key-value pairs, and the sorted values.
for k, v in data.items():
Each item is a tuple of a key and a value, which is unpacked into two variables.
$ python loop_dict.py de sk hu cz de is an abbreviation for Germany sk is an abbreviation for Slovakia hu is an abbreviation for Hungary cz is an abbreviation for Czechia Czechia Germany Hungary Slovakia
Unpacking in the loop target
The loop target can be any assignment target, including a tuple of variables, a starred name, or a nested pattern.
points = [(1, 2), (4, 3), (-2, 7)]
for x, y in points:
print(f'x={x} y={y}')
users = [('John', 'Doe', 'gardener', 34), ('Roger', 'Roe', 'driver', 51)]
for first, last, *rest in users:
print(first, last, rest)
for nr, (x, y) in enumerate(points, 1):
print(nr, x + y)
We unpack coordinate pairs and user records.
for first, last, *rest in users:
The starred name collects the remaining items into a list.
for nr, (x, y) in enumerate(points, 1):
The pair produced by enumerate contains a nested tuple, which
we unpack with parentheses.
$ python unpacking.py x=1 y=2 x=4 y=3 x=-2 y=7 John Doe ['gardener', 34] Roger Roe ['driver', 51] 1 3 2 7 3 5
Looping over several iterables with zip
The zip function iterates over several iterables in parallel
and yields tuples of their items. It stops at the shortest iterable unless
strict=True is given.
names = ['Paul', 'Lucia', 'Tom', 'Ann']
ages = [23, 31, 45, 28]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
cities = ['Bratislava', 'Kosice']
try:
for name, city in zip(names, cities, strict=True):
print(name, city)
except ValueError as e:
print('error:', e)
We pair names with ages and then names with cities.
for name, city in zip(names, cities, strict=True):
With strict=True, zip raises
ValueError when the iterables have different lengths. The
error is detected only when the shorter one runs out, so the first two
pairs are printed before it.
$ python loop_zip.py Paul is 23 years old Lucia is 31 years old Tom is 45 years old Ann is 28 years old Paul Bratislava Lucia Kosice error: zip() argument 2 is shorter than argument 1
Reversed and sorted order
The reversed function iterates over a sequence backwards and
sorted returns a new sorted list. Neither changes the original
list.
words = ['sky', 'cup', 'forest', 'war', 'atom', 'tea']
for word in reversed(words):
print(word, end=' ')
print()
for word in sorted(words):
print(word, end=' ')
print()
for word in sorted(words, key=len, reverse=True):
print(word, end=' ')
print()
print(words)
We print the words in reverse order, alphabetically, and by length from the longest.
for word in sorted(words, key=len, reverse=True):
Sorting is stable, so words of the same length keep their original order.
$ python reversed_sorted.py tea atom war forest cup sky atom cup forest sky tea war forest atom sky cup war tea ['sky', 'cup', 'forest', 'war', 'atom', 'tea']
Nested loops
A for loop can be placed inside another loop. The inner loop
runs completely in each cycle of the outer loop.
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in nums:
for e in row:
print(e, end=' ')
print()
for i in range(1, 4):
for j in range(1, 4):
print(f'{i * j:3}', end='')
print()
We print a two-dimensional list row by row and build a small multiplication table.
print(f'{i * j:3}', end='')
The format specification :3 right-aligns each product in three
characters.
$ python nested.py 1 2 3 4 5 6 7 8 9 1 2 3 2 4 6 3 6 9
The break statement
The break statement terminates the innermost loop immediately.
temps = [12.1, 13.4, 15.0, 31.7, 14.2, 33.0]
for i, t in enumerate(temps):
if t > 30:
print(f'heat alert at reading {i}: {t}')
break
print('ok', t)
We go through temperature readings and stop at the first one above 30 degrees. The readings after it are not processed.
$ python loop_break.py ok 12.1 ok 13.4 ok 15.0 heat alert at reading 3: 31.7
The continue statement
The continue statement skips the rest of the current cycle and
continues with the next item.
for num in range(1, 21):
if num % 3 == 0:
continue
print(num, end=' ')
print()
lines = ['# config', 'host=localhost', '', 'port=8080', '# end']
for line in lines:
if not line or line.startswith('#'):
continue
key, val = line.split('=')
print(f'{key} -> {val}')
The first loop prints the numbers from 1 to 20 that are not divisible by 3.
if not line or line.startswith('#'):
continue
In the second loop, we skip empty lines and comments, which keeps the main logic unindented.
$ python loop_continue.py 1 2 4 5 7 8 10 11 13 14 16 17 19 20 host -> localhost port -> 8080
The else clause
The else clause of a for loop runs when the loop
finishes because the iterable is exhausted. It is skipped when the loop is
left with break. This is useful for search loops.
def find_divisor(n):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
print(f'{n} is divisible by {d}')
break
else:
print(f'{n} is a prime')
for n in [91, 97, 121, 2]:
find_divisor(n)
We look for a divisor of a number. If one is found, the loop is ended with
break and the else block is skipped. If the loop
checks every candidate without finding one, the else block
reports a prime.
for d in range(2, int(n ** 0.5) + 1):
For 2, the range is empty; the body never runs and the else
block runs right away.
$ python loop_else.py 91 is divisible by 7 97 is a prime 121 is divisible by 11 2 is a prime
Modifying a collection while looping
Changing the size of a list while iterating over it skips elements, and changing the size of a dictionary raises an error. We iterate over a copy or build a new collection instead.
nums = [1, 2, 2, 3, 4, 4, 5]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
nums = [1, 2, 2, 3, 4, 4, 5]
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print(nums)
nums = [1, 2, 2, 3, 4, 4, 5]
nums = [n for n in nums if n % 2 != 0]
print(nums)
data = {'a': 1, 'b': 2}
try:
for k in data:
data[k.upper()] = 0
except RuntimeError as e:
print('error:', e)
We try to remove even numbers from a list in three ways.
for n in nums:
if n % 2 == 0:
nums.remove(n)
When an element is removed, the following elements shift to the left and the loop moves past one of them, so some even numbers stay in the list.
for n in nums[:]:
Iterating over a slice copy works, but the list comprehension that builds a new list is the idiomatic solution.
for k in data:
data[k.upper()] = 0
Adding keys to a dictionary during iteration raises
RuntimeError.
$ python modify_while_looping.py [1, 2, 3, 4, 5] [1, 3, 5] [1, 3, 5] error: dictionary changed size during iteration
Looping over a generator
A generator produces values lazily, one per cycle. It can even be
infinite; the loop then has to end with break, or we take a
slice with itertools.islice.
import itertools
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
for n in fibonacci():
if n > 100:
break
print(n, end=' ')
print()
for n in itertools.islice(fibonacci(), 10, 15):
print(n, end=' ')
print()
The fibonacci generator yields Fibonacci numbers forever.
for n in itertools.islice(fibonacci(), 10, 15):
The islice function skips the first ten values and stops after
the fifteenth.
$ python generator_loop.py 0 1 1 2 3 5 8 13 21 34 55 89 55 89 144 233 377
The iterator protocol
The for statement calls iter on the iterable to get
an iterator, then calls next on it until
StopIteration is raised. Any object whose
__iter__ method returns an iterator can be used in a
for loop.
words = ['sky', 'cup', 'forest']
it = iter(words)
while True:
try:
word = next(it)
except StopIteration:
break
print(word)
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
for n in Countdown(5):
print(n, end=' ')
print()
The first part does by hand what a for loop does
automatically.
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
The Countdown class implements __iter__ as a
generator method, which makes its instances iterable.
$ python iter_protocol.py sky cup forest 5 4 3 2 1
Loops with itertools
The itertools module provides building blocks that replace
common hand-written loops.
import itertools
temps = [12, 14, 13, 17, 21, 19]
for a, b in itertools.pairwise(temps):
print(f'{a} -> {b}: {b - a:+}')
for colour, size in itertools.product(['red', 'blue'], ['S', 'M', 'L']):
print(f'{colour}-{size}', end=' ')
print()
for batch in itertools.batched(range(1, 11), 4):
print(batch)
The pairwise function yields overlapping pairs of neighbouring
items, product replaces nested loops, and batched
splits an iterable into tuples of a given size; the last batch may be
shorter.
print(f'{a} -> {b}: {b - a:+}')
The + format option prints the sign for positive numbers too.
$ python itertools_loops.py 12 -> 14: +2 14 -> 13: -1 13 -> 17: +4 17 -> 21: +4 21 -> 19: -2 red-S red-M red-L blue-S blue-M blue-L (1, 2, 3, 4) (5, 6, 7, 8) (9, 10)
Loops and comprehensions
A loop that builds a new list can often be written as a list comprehension,
which uses the same for and if clauses in a single
expression.
nums = [1, 2, 3, 4, 5, 6]
squares = []
for n in nums:
if n % 2 == 0:
squares.append(n * n)
print(squares)
print([n * n for n in nums if n % 2 == 0])
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([e for row in matrix for e in row])
print([*row for row in matrix])
The loop and the first comprehension produce the same list of squares of even numbers.
print([e for row in matrix for e in row]) print([*row for row in matrix])
Two for clauses flatten a nested list; they are read in the
same order as nested loops. Python 3.15 adds unpacking in comprehensions
(PEP 798), so [*row for row in matrix] does the same. See
Python comprehension
unpacking.
$ python comprehension.py [4, 16, 36] [4, 16, 36] [1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Looping over a file
A file object is an iterator over its lines, so we can read a text file line
by line with a for loop without loading it into memory. We use
the following file.
sky blue forest rock
The file contains four words, one per line.
with open('words.txt', encoding='utf-8') as f:
for nr, line in enumerate(f, 1):
print(nr, line.rstrip())
Each line includes the trailing newline character, which we remove with
rstrip.
$ python read_lines.py 1 sky 2 blue 3 forest 4 rock
Source
The for statement – Python language reference
for statements – Python tutorial
In this article we have worked with the Python for loop. See
also Python list loop,
Python iterators,
Python list comprehensions, and
Python map.
Author
List all Python tutorials.