The for loop in Python: iterating over a sequence

The for loop walks through the items of a sequence one by one: no counter to manage, no stop condition to write, no length to know in advance.
5 min read
Believemy logo

Definition

Programming very often means repeating the same gesture on every item of a collection: printing each name from a list, cleaning each line of a file. Copying the same statement as many times as there are items would mean knowing that number in advance, which rarely happens.

The for loop solves that problem: it goes through the items of a sequence one by one and runs the same block for each of them, whatever their number. Where other languages ask for a counter, a stop condition and an increment, Python only asks for the thing to walk through. It is the most used loop in the language.

PYTHON
for name in ["Camille", "Sacha", "Noa"]:
    print("Hello", name)        # runs once per name

The name variable takes each value of the list in turn. It does not need to exist beforehand: the loop creates it, and its name is yours to choose, so choose a telling one.

That leaves the question of where the repeated block ends. The shift to the right says it: what follows the colon and stays indented belongs to the loop. indentation is therefore part of the meaning of the program.


What for can walk through

The next question is almost always the same: is this reserved for lists? No, for accepts anything that can be visited item by item, which Python calls an iterable. What the variable receives depends on the object walked, as this table shows.

Object walked throughWhat the variable receives
A list or a tupleEach item, in order
A stringEach character, one at a time
A dictionaryEach key, not the value
A setEach item, in no guaranteed order
An open fileEach line, line break included

The dictionary row catches a lot of people out: the walk hands over the keys only. The values are asked for with .values(), both at once with .items().

Forgetting it is paid straight away: a loop written in the belief that it receives values is really working on keys, and nothing announces it before an impossible operation gives it away. Hence a good share of the early KeyError.

Warning

Lines read from a file keep their line break stuck to the end. Comparing a line to an expected word therefore always fails, with no error message. Run it through .strip() before comparing, or the mistake will stay invisible.


The counter trap

Coming from another language, the reflex is to count up to the length of the list, then read each item by its index. The code works, but it redoes by hand the job of for.

PYTHON
colours = ["red", "green", "blue"]

# Works, but nobody writes this in Python
for i in range(len(colours)):
    print(colours[i])           # i only exists to fetch the item back

# What people write: the loop hands over the item directly
for colour in colours:
    print(colour)

# And when the position really matters, enumerate gives both
for rank, colour in enumerate(colours, start=1):
    print(rank, colour)         # 1 red, 2 green, 3 blue

The first two loops print the same thing. What separates them is that only one juggles numbers: a counter, a length, then an access by index. Three chances to get it wrong where the second offers none.

That leaves the case where the position really matters, to number an output for instance. This is the job of enumerate, which returns the position and the item on each pass, with a start to count from 1. The number is there without ever indexing the list, and so without risking the IndexError.

Good to know

When a loop exists only to build a new list from another one, Python offers a denser form, the list comprehension. It accepts neither an early exit nor a multi-line block.


Leaving early or skipping a turn

A loop does not always run to the end. break leaves it on the spot, without looking at the remaining items: what a search wants, since carrying on after finding only wastes time.

continue is gentler: it drops the current pass and moves on to the next one. The cases to ignore are pushed aside at the top of the block, instead of wrapping all the rest in a condition.

A third form comes as a surprise: else can attach to a loop, not only to an if. Its block runs only when the loop reached its end without meeting a break: the ideal place to report that a search found nothing.


Frequently asked questions

Question

What is the difference between for and while in Python?

A for loop walks through a collection whose content already exists: the number of passes is settled when it starts. while repeats as long as a condition holds true, with no way of knowing how many passes that takes, which suits user input. As soon as a collection is involved, for is the call.

Question

Can a list be modified while it is being walked through?

It is possible, and it is a very bad idea. Removing an item shifts everything after it by one place, while the loop moves forward one position on each pass: every other item is silently skipped, with no warning. Build a new list instead.

Question

Does the loop variable still exist after the for?

Yes: it outlives the loop and keeps the last value visited, which can suggest a computation worked when the loop only ran once. On an empty sequence, conversely, it is never created and reading it raises a NameError. The loop is what turns a list of instructions into a program that handles data: our Python course works through it on real files from the first sessions onwards.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.