ZetCode

Python list loop

last modified November 16, 2026 Python 3.15

In this article we show how to loop over lists in Python.

A loop is a sequence of instructions that is repeated until a certain condition is reached. A list is an ordered collection of items, and going through its elements one by one is one of the most common operations in Python programs. We can loop over list elements with the for and while statements, and transform lists with comprehensions. Built-in functions such as enumerate, zip, reversed, and sorted, and the itertools module give us more control over the iteration.

Looping with for

The for statement iterates over the elements of a list in the order in which they appear in the list. In each cycle, the loop variable is bound to the next element.

for_loop.py
words = ['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

for word in words:
    print(word)

The example goes over the elements of a list of words with the for statement and prints each of them. There is no index variable; the loop works directly with the elements.

$ python for_loop.py
cup
star
falcon
cloud
wood
door

break and continue

The continue statement skips the rest of the current cycle and moves on to the next element. The break statement terminates the loop completely.

break_continue.py
vals = [4, -2, 7, 0, 11, -5, 3, 9]

for val in vals:
    if val < 0:
        continue
    if val > 10:
        print(f'{val} is too large, stopping')
        break
    print(val)

The loop prints non-negative values. Negative values are skipped with continue; the first value larger than ten stops the loop with break, so the remaining values -5, 3, and 9 are never examined.

$ python break_continue.py
4
7
0
11 is too large, stopping

The else clause

The for loop has an optional else clause. Its body runs when the loop finishes normally, that is, when it was not terminated by break. This makes it useful for search loops.

for_else.py
def find_word(words, prefix):
    for word in words:
        if word.startswith(prefix):
            print(f'found {word}')
            break
    else:
        print(f'no word starts with {prefix!r}')


words = ['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

find_word(words, 'fa')
find_word(words, 'sk')

The find_word function looks for the first word with the given prefix. When a word is found, the loop is terminated with break and the else block is skipped. When the loop runs out of words, the else block reports that nothing was found.

$ python for_else.py
found falcon
no word starts with 'sk'

Looping with enumerate

The enumerate function lets us loop over list elements together with their indexes. It yields pairs of an index and an element, which we unpack into two loop variables.

enumerate_loop.py
words = ['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

for idx, word in enumerate(words):
    print(f'{idx}: {word}')

print()

for n, word in enumerate(words, start=1):
    print(f'{n}. {word}')

The first loop prints each element with its zero-based index. The optional start parameter sets the first number of the counter; with start=1 we get a numbered list as people usually write it.

$ python enumerate_loop.py
0: cup
1: star
2: falcon
3: cloud
4: wood
5: door

1. cup
2. star
3. falcon
4. cloud
5. wood
6. door

Looping over indexes with range

Sometimes we need the indexes themselves, for example to replace elements in place or to compare an element with its neighbour. The range(len(vals)) idiom produces the valid indexes of a list.

range_index.py
vals = [3, 5, 8, 2, 9, 1]

for i in range(len(vals)):
    vals[i] *= 10

print(vals)

for i in range(1, len(vals)):
    print(f'{vals[i - 1]} -> {vals[i]}: {vals[i] - vals[i - 1]:+d}')

The first loop multiplies every element by ten. Assigning to the loop variable of a plain for word in words loop would not change the list; assigning to vals[i] does. The second loop starts at index 1 and compares each element with the previous one.

When only the elements are needed, the plain for loop or enumerate is clearer than indexing.

$ python range_index.py
[30, 50, 80, 20, 90, 10]
30 -> 50: +20
50 -> 80: +30
80 -> 20: -60
20 -> 90: +70
90 -> 10: -80

Looping with while

The while statement repeats its body as long as a condition is true. With lists it is used when the loop is driven by an index we manage ourselves, or when the list shrinks during the loop.

while_loop.py
vals = [1, 2, 3, 4, 5, 6, 7]

i = 0
total = 0

while i < len(vals):
    total += vals[i]
    i += 1

print(f'The sum is {total}')

tasks = ['wash', 'cook', 'clean']

while tasks:
    task = tasks.pop(0)
    print(f'doing {task}, {len(tasks)} left')

The first loop computes the sum of the values with an explicit index. (The built-in sum function does the same in one call.)

while tasks:
    task = tasks.pop(0)

The second loop processes a list of tasks until it is empty. An empty list is falsy, so while tasks ends the loop once the last task has been removed with pop.

$ python while_loop.py
The sum is 28
doing wash, 2 left
doing cook, 1 left
doing clean, 0 left

Looping in reverse and sorted order

The reversed function returns an iterator that goes over a list from the last element to the first. The sorted function returns a new sorted list. Neither of them modifies the original list.

reversed_sorted.py
words = ['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

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 loop over the words backwards, in alphabetical order, and by length from the longest. The key parameter of sorted selects the value to compare and reverse=True reverses the order. Words of equal length keep their original order because Python's sort is stable. The last line shows that the words list itself is unchanged.

$ python reversed_sorted.py
door wood cloud falcon star cup 
cloud cup door falcon star wood 
falcon cloud star wood door cup 
['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

Looping over several lists with zip

The zip function takes several iterables and yields tuples of their corresponding elements. It lets us loop over several lists in parallel.

zip_loop.py
names = ['Paul', 'Lucy', 'Robert', 'Monica']
ages = [34, 28, 51, 45]
cities = ['Bratislava', 'Prague', 'Vienna', 'Budapest']

for name, age, city in zip(names, ages, cities):
    print(f'{name} ({age}) lives in {city}')

ages.pop()

try:
    for name, age in zip(names, ages, strict=True):
        print(name, age)
except ValueError as e:
    print(f'error: {e}')

We loop over three lists at once. By default, zip stops when the shortest iterable is exhausted, which can silently hide missing data.

for name, age in zip(names, ages, strict=True):

After removing the last age, the lists have different lengths. With strict=True, zip raises a ValueError when it detects the mismatch. Note that the error is raised only after the pairs before it have been produced.

$ python zip_loop.py
Paul (34) lives in Bratislava
Lucy (28) lives in Prague
Robert (51) lives in Vienna
Monica (45) lives in Budapest
Paul 34
Lucy 28
Robert 51
error: zip() argument 2 is shorter than argument 1

Nested lists

A list can contain other lists. To go over the elements of a two-dimensional list, we use two nested for loops.

nested_loop.py
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in grid:
    for val in row:
        print(f'{val:3}', end='')
    print()

for i, row in enumerate(grid):
    for j, val in enumerate(row):
        if i == j:
            print(f'diagonal [{i}][{j}] = {val}')

The outer loop goes over the rows; the inner loop goes over the values of a row. The end='' argument keeps the values of a row on one line. In the second part, we combine nested loops with enumerate to get the row and column indexes and print the elements on the main diagonal.

$ python nested_loop.py
  1  2  3
  4  5  6
  7  8  9
diagonal [0][0] = 1
diagonal [1][1] = 5
diagonal [2][2] = 9

Modifying a list while looping

Removing elements from a list while iterating over it is a common mistake. The loop keeps an internal index; when an element is removed, the following elements shift to the left and the loop skips one of them.

modify_while_looping.py
vals = [1, 2, 2, 3, 4, 4, 5]

for val in vals:
    if val % 2 == 0:
        vals.remove(val)

print(f'wrong: {vals}')

vals = [1, 2, 2, 3, 4, 4, 5]

for val in vals[:]:
    if val % 2 == 0:
        vals.remove(val)

print(f'copy: {vals}')

vals = [1, 2, 2, 3, 4, 4, 5]
vals = [val for val in vals if val % 2 != 0]

print(f'comprehension: {vals}')

We want to remove all even numbers. The first loop leaves 2 and 4 in the list: after the first 2 is removed, the second 2 moves to its position and the loop jumps over it.

for val in vals[:]:

Looping over a copy created with the [:] slice fixes the problem, because the copy does not change during the loop. The cleanest solution is to build a new list with a comprehension that keeps only the wanted elements.

$ python modify_while_looping.py
wrong: [1, 2, 3, 4, 5]
copy: [1, 3, 5]
comprehension: [1, 3, 5]

List comprehensions

A list comprehension is a compact way to loop over a list and build a new list from its elements. A generator expression works similarly but produces the values lazily, which suits functions such as sum, min, or any.

comprehension.py
words = ['cup', 'star', 'falcon', 'cloud', 'wood', 'door']

lengths = [len(word) for word in words]
print(lengths)

long_words = [word.upper() for word in words if len(word) > 4]
print(long_words)

total = sum(len(word) for word in words)
print(total)

The first comprehension computes the length of each word. The second one filters the words with a condition and transforms the remaining ones to uppercase. Finally, a generator expression passed to sum adds up the lengths without creating an intermediate list.

Comprehensions are meant for building new lists. For side effects such as printing, use a regular for loop.

$ python comprehension.py
[3, 4, 6, 5, 4, 4]
['FALCON', 'CLOUD']
26

Pairs and batches with itertools

The itertools module provides iterator building blocks. The pairwise function yields overlapping pairs of consecutive elements and batched (added in Python 3.12) splits the data into tuples of a given size.

pairwise_batched.py
from itertools import batched, pairwise

temps = [12, 15, 14, 18, 21, 19, 17]

for prev, cur in pairwise(temps):
    print(f'{prev:2} -> {cur:2} ({cur - prev:+d})')

print()

for week in batched(range(1, 11), 3):
    print(week)

With pairwise, we compute the change between consecutive temperatures without any index arithmetic. The batched function groups ten numbers into tuples of three; the last tuple holds the remaining element.

$ python pairwise_batched.py
12 -> 15 (+3)
15 -> 14 (-1)
14 -> 18 (+4)
18 -> 21 (+3)
21 -> 19 (-2)
19 -> 17 (-2)

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10,)

Source

for statements – Python tutorial

Looping techniques – Python tutorial

In this article we have looped over lists in Python. See also Python for loop, Python list comprehensions, and Python itertools.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.