A loop in Python: repeating without rewriting

A loop repeats a block of code as many times as needed: over the items of a collection with for, or for as long as a condition holds true with while.
5 min read
Believemy logo

Definition

A program that handles a thousand orders does not contain a thousand shipping lines. Copying the same statement once per piece of data would be impossible to maintain, and even to write: when you type the code, you have no idea how many orders will turn up. That is the problem a loop solves.

A loop repeats a block of code without it having to be rewritten. You describe the work once, and Python replays it as many times as needed. It is what lets a fifteen-line program handle a ten-thousand-line file.

Python offers two forms, and choosing between them is not a matter of taste: it depends on what you know when the loop is entered.

PYTHON
# Case 1: we know the collection, so we know the number of turns
for order in orders:
    ship(order)

# Case 2: we do not know the number of turns,
# only the condition that makes us stop
while not connection.is_open:
    try_reconnect()


Choosing between the two

The question is always the same: do I already know what I am going to walk through? The table below sets the two forms against each other on the four points that settle it.

forwhile
What it needsA collection to walk throughA stop condition
Number of turnsKnown upfrontUnknown
Main riskNone, it stops on its ownThe infinite loop
Typical useA list, a file, a dictionaryA wait, an input, a state

As soon as a collection is involved, use for: the collection knows its own length, so the loop stops by itself. while is kept for cases where the end depends on something that can only be judged after acting, such as an answer from the user or a server that is not responding yet: before acting, you cannot know whether that was the last turn.

That leaves the case everyone thinks of straight away: no collection at all, just a known number of repetitions. It still belongs to for, which then needs something to walk through: that is the job of range.

Good to know

Python's for is not the counter other languages give you. It counts nothing: it asks an iterable to hand over its items one at a time. Hence no index to manage, and hence range, for when you genuinely want numbers.


Steering the walk

A loop that always runs to the end stops being enough quite quickly: as soon as you are looking for one particular item, carrying on after finding it makes no sense. Three statements take back control.

break leaves the loop straight away, without finishing the current turn. That is what turns a full walk into a search: over ten thousand items, stopping at the right moment reads half of them on average.

continue drops the current turn and moves on to the next. It rules out the cases you are not interested in right at the top, without wrapping the whole loop body in an if: one level of indentation saved, and the main logic stays readable.

The loop else, a Python speciality, throws everyone on first contact. It does not mean "otherwise": it runs when the loop reached its end without ever meeting a break. It is the "I found nothing" block.

On top of those sit the functions that enrich a walk. enumerate supplies the position alongside the item, which removes the hand-incremented counter. zip walks two collections in parallel, the case where people are wrongly tempted to fall back on indices.

Warning

Never remove items from a list while you are walking through it. Every deletion shifts the following ones along, so the loop skips every other item, and nothing flags the anomaly: the program finishes normally, with a wrong result. Walk through a copy of the list instead.


When to do without one

Not every repetition deserves a hand-written loop. The most frequent case is also the most mechanical: taking one collection and building another out of it, item by item. Python has a dedicated form for that, the list comprehension.

PYTHON
# A loop that only accumulates:
# three lines to say "multiply every price"
gross_prices = []
for price in net_prices:
    gross_prices.append(price * 1.2)

# The same thing, on one line
gross_prices = [price * 1.2 for price in net_prices]

What the second version gains is not brevity, it is intent: it announces from the very first character that a list is being built, where the first one makes you read three lines.

The test is simple: if the loop body comes down to an append, the comprehension wins. As soon as there are several operations, cases to rule out with an explanation or an exception to catch, the explicit loop becomes the right answer again.


Frequently asked questions

Question

How do you get out of an infinite loop?

While it runs, the keyboard interrupt stops the program, Control and C on most systems. In the code, the cause is nearly always a control variable never changed inside the body, or changed in a branch that a continue placed above keeps out of reach.

Question

Can loops be nested?

Yes, and it is common for walking a grid or crossing two collections. Mind the cost: two nested loops over a thousand items each make a million turns. When the inner loop only serves to find the matching item, a dictionary built before the walk replaces that pass with an immediate lookup.

Question

How do you repeat an action a fixed number of times?

With for and range, for instance for _ in range(5):. The underscore is the convention for saying the counter value is not used, only the number of repetitions matters. Knowing which of the two loops to reach for, and spotting when a comprehension beats both, is worked through on real cases in our Python course.

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.