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 tutorial 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:

  • Method 1: 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).
  • Method 2: 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.

Check out my new Python book Python One-Liners (Amazon Link).

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 was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

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

Method 1: Single-Line For Loop

Just writing the for loop in a single line is the most direct way of accomplishing the task. After all, Python doesn’t need the indentation levels to resolve ambiguities when the loop body consists of only one line.

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 right 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:

Method 2: List Comprehension

List Comprehension

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

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 fewer bits.

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

Also, feel free to watch the video 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.

Method 3: Python One Line For Loop With If

You can also modify the list comprehension statement by restricting the context with another if statement:

Problem: Say, we want to create a list of squared numbers—but you only consider even and ignore odd numbers.

Example: The multi-liner way would be the following.

squares = []

for i in range(10):
    if i%2==0:
        squares.append(i**2)
    
print(squares)
# [0, 4, 16, 36, 64]

You create an empty list squares and successively add another square number starting from 0**2 and ending in 8**2—but only considering the even numbers 0, 2, 4, 6, 8.

Thus, the result is the list [0, 4, 16, 36, 64].

Again, you can use list comprehension [i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code.

See here:

print([i**2 for i in range(10) if i%2==0])
# [0, 4, 16, 36, 64]

This line accomplishes the same output with much fewer bits.

Related Article: Python One-Line For Loop With If

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

You can see the error message in the following screenshot:

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 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.

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd