Python for Loop in One Line (One-Liner Examples)

A Python for loop on one line can be written two ways: put a short body after the colon, like for x in items: print(x), or, when you’re building a new list, use a comprehension such as [x * 2 for x in items]:

for city in cities: print(city)          # one-line loop
doubled = [n * 2 for n in numbers]        # one-line loop that builds a list

I ran each one-liner on Python 3.12.5, and the screenshots come straight from Command Prompt.

You’ll see single-line loops, list, dict and set comprehensions, if-else inside them, generator expressions, nested loops, the one-liners to avoid, and how much faster comprehensions are.

Writing a for loop on one line

Python lets you put a simple statement right after the colon. It’s fine for one short action, like printing or adding to a running total:

cities = ["Austin", "Denver", "Boston"]

for city in cities: print(city.upper())           # a for loop on one line

for i, city in enumerate(cities, 1): print(i, city, sep=". ")

prices = [19.99, 4.50, 102.00]
total = 0.0
for p in prices: total += p
print(f"total ${total:.2f}")

Output:

AUSTIN
DENVER
BOSTON
1. Austin
2. Denver
3. Boston
total $126.49
Command Prompt output of Python for loops written on one line printing uppercase cities, numbered cities and a running total
Each loop body fits after the colon. Anything longer belongs on its own indented lines.

PEP 8, Python’s style guide, discourages this for anything but very short bodies, so most code uses the indented form. See the Python for loop guide for the full syntax.

One-line for loops with list comprehensions

When the loop’s job is to build a collection, a comprehension is the idiomatic one-liner. Add if at the end to filter, or an if-else expression at the front to transform:

prices = [19.99, 4.50, 102.00, 12.75]

with_tax = [round(p * 1.08, 2) for p in prices]                 # list comprehension
cheap = [p for p in prices if p < 20]                          # with a filter
labels = ["sale" if p < 20 else "full price" for p in prices]  # if-else in the expression
by_name = {name: len(name) for name in ["Ava", "Benjamin"]}    # dict comprehension
states = {s.upper() for s in ["tx", "ca", "tx", "ny"]}          # set comprehension

print(with_tax)
print(cheap)
print(labels)
print(by_name)
print(sorted(states))

Output:

[21.59, 4.86, 110.16, 13.77]
[19.99, 4.5, 12.75]
['sale', 'sale', 'full price', 'sale']
{'Ava': 3, 'Benjamin': 8}
['CA', 'NY', 'TX']
Command Prompt output of Python list, filtered list, if-else, dict and set comprehensions on prices and state codes
Lists, dicts and sets all have comprehension forms. Note where if goes for filtering versus choosing a value.

The rule is easy to remember: a filter if goes after the loop, while x if cond else y goes before it. More examples in list comprehension with if-else.

One-liners with sum(), any() and all()

Drop the square brackets and you get a generator expression, which feeds values one at a time without building a list. It’s perfect inside functions that consume a sequence:

orders = [42.50, 18.00, 120.25, 7.99]

print(f"total: ${sum(o for o in orders):.2f}")            # no list built in memory
print("any over $100?", any(o > 100 for o in orders))
print("all over $5?  ", all(o > 5 for o in orders))
print("biggest:", max(orders, key=lambda o: o))
print(", ".join(f"${o:.2f}" for o in orders))

Output:

total: $188.74
any over $100? True
all over $5?   True
biggest: 120.25
$42.50, $18.00, $120.25, $7.99
Command Prompt output of Python generator expressions with sum, any, all, max and join on a list of order totals
Totals, checks and formatting, each in a single line.

any() and all() also stop early once the answer is known. There’s more on sum() in the sum() function in Python.

Nested loops on one line

Comprehensions can contain more than one for. They run in the same order as nested loops written out normally, outer loop first:

grid = [[r * 3 + c for c in range(3)] for r in range(3)]       # build a 3x3 grid
print(grid)
print([n for row in grid for n in row])                         # flatten: outer loop first
print([(s, size) for s in ["TX", "CA"] for size in ["S", "M"]]) # every combination

Output:

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[('TX', 'S'), ('TX', 'M'), ('CA', 'S'), ('CA', 'M')]

Two levels is usually the limit before a one-liner gets hard to read. For grids, list of lists in Python has more patterns.

One-liners to avoid

A comprehension used only for its side effects builds a list you throw away, and semicolons cram several statements together. Both work, but they make code harder to read:

cities = ["Austin", "Denver"]

result = [print(c) for c in cities]       # works, but builds a useless list of None
print(result)

for c in cities: print(c); print("---")   # semicolons: legal, but hard to read

Output:

Austin
Denver
[None, None]
Austin
---
Denver
---

If you’re not using the result, write a regular for loop. Comprehensions are for making new values.

Is a one-line for loop faster?

A list comprehension is usually a bit faster than a for loop with append(), because it skips the method call per item. Here’s what I measured on 100,000 numbers:

import timeit

nums = list(range(100_000))

def loop():
    out = []
    for n in nums:
        out.append(n * 2)
    return out

def comp():
    return [n * 2 for n in nums]

print("same result:", loop() == comp())
print(f"for loop + append: {timeit.timeit(loop, number=100):.3f} s")
print(f"comprehension:     {timeit.timeit(comp, number=100):.3f} s")

Output:

same result: True
for loop + append: 0.432 s
comprehension:     0.332 s
Command Prompt output timing a Python for loop with append against an equivalent list comprehension
Same result; the comprehension was roughly 10% faster in this run. The gap varies by Python version and workload.

Putting a regular loop on one line doesn’t speed it up at all. I pick comprehensions mainly because they’re clearer for building lists; the speed is a bonus.

Python one-line loop cheat sheet

GoalOne-liner
Do something for each itemfor x in items: print(x)
Transform into a list[f(x) for x in items]
Filter[x for x in items if x > 0]
Choose a value["hi" if x > 0 else "lo" for x in items]
Total or checksum(x for x in items), any(x > 0 for x in items)
Build a dict{k: v for k, v in pairs}

More loop tutorials you might like:

Frequently asked questions

How do I write a for loop in one line in Python?

Put the body after the colon, like for x in items: print(x), or use a comprehension such as [x * 2 for x in items] to build a list.

Can I use if-else in a one-line for loop?

Yes, inside a comprehension: ["even" if n % 2 == 0 else "odd" for n in nums].

Is a list comprehension faster than a for loop?

Usually a little, for building lists. A plain loop written on one line isn’t any faster than the indented version.

How do I write nested loops in one line?

Chain the for clauses in a comprehension, outer first: [n for row in grid for n in row].

Should I use one-line loops everywhere?

No. Use them when they’re short and clear. If you need several statements, write a normal loop.

Where are comprehensions documented?

See List Comprehensions in the Python tutorial.