Python One Line For Loop [A Simple Tutorial]

Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a for loop in a single line of code? This article explores this mission-critical question in all detail.

How to Write a For Loop in a Single Line of Python Code?

There are two ways of writing a one-liner for loop:

  • If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i). This prints the first 10 numbers to the shell (from 0 to 9).
  • If the purpose of the loop is to create a list, use list comprehension instead: squares = [i**2 for i in range(10)]. The code squares the first ten numbers and stores them in the list squares.

Let’s have a look at both variants in more detail.

But before you and I move on, I’m excited to present you my brand-new Python book Python One-Liners.

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

But enough promo, let’s dive into the first method—the profane…

Single-Line For Loop

Just writing the for loop into a single line of code is the most direct way of accomplishing the task.

Say, we want to write the following for loop in a single line of code:

>>> for i in range(10):
	print(i)

	
0
1
2
3
4
5
6
7
8
9

We can easily get this done by writing the command into a single line of code:

>>> for i in range(10): print(i)

0
1
2
3
4
5
6
7
8
9

While this answer seems straightforward, the interesting question is: can we write a more complex for loop that has a longer loop body in a single line?

This is much more difficult. While it’s possible to condense complicated algorithms in a single line of code, there’s no general formula. If you’re interested in compressing whole algorithms into a single line of code, check out this article with 10 Python one-liners that fit into a single tweet.

Suppose, you have the following more complex loop:

for i in range(10):
    if i<5:
        j = i**2
    else:
        j = 0    
    print(j)

This generates the output:

0
1
4
9
16
0
0
0
0
0

Can we compress it into a single line? The answer is yes! Check out the following code snippet:

for i in range(10): print(i**2 if i<5 else 0)

This generates the same output as our multi-line for loop. As it turns out, we can use the ternary operator in Python that allows us to compress an if statement into a single line. Check out this tutorial on our blog if you want to learn more about the exciting ternary operator in Python. The ternary operator is very intuitive: just read it from left to write to understand its meaning. In the loop body print(i**2 if i<5 else 0) we print the square number i**2 if i is smaller than 5, otherwise, we print 0.

Let’s explore an alternative Python trick that’s very popular among Python masters:

List Comprehension

Being hated by newbies, experienced Python coders can’t live without this awesome Python feature.

Say, we want to create a list of squared numbers. The traditional way would be to write something along these lines:

squares = []

for i in range(10):
    squares.append(i**2)
    
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We create an empty list squares and successively add another square number starting from 0**2 and ending in 9**2. Thus, the result is the list [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].

List comprehension condenses this into a single line of code–that is also readable, more efficient, and concise.

print([i**2 for i in range(10)])

This line accomplishes the same output with much less bits.

A thorough tutorial of list comprehension can be found at this illustrated blog resource.

Watch an interactive video tutorial in my list comprehension tutorial:

List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

  • Expression: What to do with each list element?
  • Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The first part is the expression. In the example above, it was the expression i**2. Use any variable in your expression that you have defined in the context within a loop statement.

The second part is the context. In the example above, it was the expression for i in range(10). The context consists of an arbitrary number of for and if clauses. The single goal of the context is to define (or restrict) the sequence of elements on which we want to apply the expression.

Related Questions

Let’s dive into some related questions that might come to your mind.

What’s a Generator Expression?

A generator expression is a simple tool to generate iterators. If you use a for loop, you often iterate over an iterator. For instance, a generator expression does not explicitly create a list in memory. Instead, it dynamically generates the next item in the iterable as it goes over the iterable. We used a generator expression in the print() statement above:

print(i**2 if i<5 else 0)

There are no squared brackets around the generator expression as it’s the case for list comprehensions.

How to Create a Nested For Loop in One Line?

We cannot write a simple nested for loop in one line of Python.

Say, you want to write a nested for loop like the following in one line of Python code:

for i in range(3):
    for j in range(3):
        print((i,j))

'''
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
'''

When trying to write this into a single line of code, we get a syntax error:

for i in range(3): for j in range(3): print((i,j))
# Syntax Error

However, we can create a nested list comprehension statement.

print([(i,j) for i in range(3) for j in range(3)])
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),
# (1, 2), (2, 0), (2, 1), (2, 2)]

This only leads to a slightly more complex context part for i in range(3) for j in range(3). But it’s manageable.

Where to Go From Here

Knowing small Python one-liner tricks such as the list comprehension and single-line for loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.

If you want to learn the language Python by heart, join my free Python email course. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.