Python for Loop in One Line

Tech reviewed: Deepak Prasad
Python for Loop in One Line

In Python, the usual “one-line for” is a list comprehension: an expression inside brackets, then a for clause, then optional extra for or if parts. The language reference spells out that structure.

Use a comprehension when you are building a new list (or dict/set variant) from an iterable. Use a normal multi-line for loop when the logic grows, needs side effects, or deserves step-by-step readability.

python
numbers = [1, 2, 3, 4]

squares = [n * n for n in numbers]

print(squares)
Output

You should see [1, 4, 9, 16]. That is a list comprehension: the shortest readable form for “make a new list from this loop.”

For broader comprehension patterns, the dedicated list comprehension in Python guide goes deeper. When a one-liner’s only job is a yes/no scan, any() / all() with a generator can be clearer—see Python any() and all().

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Can you write a for loop in one line in Python?

Yes. For building collections, use comprehensions or generator expressions. For arbitrary statements, you can separate simple statements with semicolons, but that does not scale—prefer a block for when behavior is more than a single expression.


One-line for loop syntax in Python

List comprehension shape:

text
[expression for target in iterable]
[expression for target in iterable if condition]

Dictionary and set comprehensions swap the brackets for { } and use key: value in the expression position. Generator expressions use parentheses: (expression for target in iterable).


Python one-line for loop with list comprehension

The for clause drives iteration; the leading expression transforms each value.

python
words = ["a", "bb", "ccc"]
lengths = [len(w) for w in words]
print(lengths)
Output

You should see [1, 2, 3].


Python one-line for loop with if condition

Put if at the end to filter which elements are kept.

python
nums = [1, -2, 3, -4]
positives = [n for n in nums if n > 0]
print(positives)
Output

You should see [1, 3].


Python one-line for loop with if else

Use a conditional expression in the leading part when every iteration must produce a value, but the value depends on a test.

python
nums = [1, -2, 3]
clamped = [n if n > 0 else 0 for n in nums]
print(clamped)
Output

You should see [1, 0, 3]. That differs from if at the end, which drops items instead of substituting.


One-line for loop without creating a list

Parentheses make a generator expression—lazy, memory-friendly, consumed once unless you copy it.

python
nums = [1, 2, 3, 4]
squares_gen = (n * n for n in nums)
print(list(squares_gen))
Output

You should see [1, 4, 9, 16]. Pass the generator to functions like sum() or max() when you do not need the whole list.


One-line for loop with print()

Avoid [print(x) for x in items] for real code: it constructs a list of None values while printing. Use a regular loop or call print in a small block.

python
for x in [1, 2, 3]:
    print(x)
Output

You should see three lines 1, 2, 3.


One-line for loop with dictionary

Use dict comprehension {key_expr: value_expr for ...}.

python
scores = {"Ada": 10, "Bob": 9}
doubled = {name: points * 2 for name, points in scores.items()}
print(doubled)
Output

You should see {'Ada': 20, 'Bob': 18}. For dict basics, see Python dictionary example.


One-line for loop with enumerate()

Pair each index with the value in one expression.

python
items = ["x", "y"]
lines = [f"{i}:{v}" for i, v in enumerate(items)]
print(lines)
Output

You should see ['0:x', '1:y']. See Python enumerate() for the full API (start, and so on).


One-line for loop with nested loops

Extra for clauses read left-to-right like nested loops.

python
pairs = [(i, j) for i in range(1, 3) for j in range(1, 3)]
print(pairs)
Output

You should see [(1, 1), (1, 2), (2, 1), (2, 2)].


One-line for loop vs normal for loop

Prefer a comprehension when Prefer a normal for when
You build a list/dict/set from a simple transform You need several statements per iteration
Logic fits one readable expression You handle exceptions or non-trivial control flow
No persistent side effects inside the expression You mutate external state deliberately

Common mistakes with one-line for loops

  • Nesting so many for / if clauses that the line becomes unreadable—split into a helper function or a block loop.
  • Using [print(x) for x in data] and forgetting it allocates a list of None.
  • Confusing trailing if (filter) with a conditional expression (map every slot).
  • Capturing mutable defaults or loop variables in lambdas inside comprehensions without understanding closure timing.
  • Expecting a generator expression to be rewindable—it is single-pass unless recreated.
  • Putting heavy I/O or database work inside a comprehension—side effects hide in expressions and are hard to debug.

Python one-line for loop quick reference table

Goal Form
New list [expr for x in iterable]
Filter list [expr for x in iterable if cond]
Map with fallback [a if cond else b for x in iterable]
Lazy stream (expr for x in iterable)
New dict {k: v for k, v in iterable}
Index + value [f(i, x) for i, x in enumerate(items)]

Summary

The idiomatic “one-line for” in Python is usually a list, dict, or set comprehension, or a generator expression when you want laziness. Comprehensions excel at building collections from simple rules; switch to a standard for loop when the body needs room to breathe. Know the difference between a filtering if at the end and a conditional expression in the head, and reserve print loops for regular block syntax.


References


Frequently Asked Questions

1. Is a list comprehension the same as a for loop?

It is syntactic sugar for a common for-loop pattern that builds a list; the interpreter still loops, but the intent is visible in one expression.

2. When should I not use a one-line comprehension?

Skip it when the body needs many statements, exception handling, or side effects beyond building a collection—use a normal multi-line for loop instead.

3. What is the difference between [x for x in data if cond] and [expr for x in data]?

An if at the end filters which elements are kept; a conditional expression inside the leading expression chooses per-element values for every iteration.

4. Does a generator expression build a list?

No—parentheses yield a lazy iterator; wrap in list() only when you need all values in memory at once.

5. Why does [print(x) for x in items] feel wrong?

It builds a list of None results while printing; a plain for loop or explicit iteration is clearer for side effects.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models.

  • Python with Projects
  • C Programming
  • Master of the Basics Python Tkinter
  • Python (programming language)
  • Java (programming language)
  • Machine Learning