Python Tuple Comprehension: Step-by-Step Guide (Examples)

In Python, there’s no tuple comprehension.

However, you can mimic the tuple comprehensions by running a generator expression inside tuple() function call.

For example:

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

# 'Tuple comprehension'
squares = tuple(x**2 for x in numbers)

print(squares)  # Output: (1, 4, 9, 16, 25)

This guide teaches you how to mimic the behavior of tuple comprehensions by using generator expressions inside the tuple() function.

You will learn what is a generator expression and how the tuple() function works with a generator expression. Besides, you’ll also learn why you should not do tuple comprehensions if you care about performance.

Let’s jump into it!

How Does It Work?

There are no tuple comprehensions in Python. Syntactically, however, there’s a close alternative!

To create a tuple with a syntax that resembles a tuple comprehension in Python, you can place a generator expression inside a tuple() function call.

values = tuple(elem for elem in iterable)

You already saw an example of this in the introduction. But let’s take a closer look at how it works.

1. What Is a Generator Expression in Python?

In Python, a generator expression is a concise way to create a generator object. It is similar to list comprehension, but instead of creating a list, it creates a generator.

A generator is an iterator that generates values on the fly, rather than storing them in memory. This makes it more efficient, especially when working with large collections of data. Read more about generators here.

Here is an example of a generator expression:

# Create a generator that generates the squares of numbers from 1 to 10
squares = (x**2 for x in range(1, 11))

To use the values generated by a generator, you can loop over it using a for loop.

for square in squares:
    print(square)

Output:

1
4
9
16
25
36
49
64
81
100

Alternatively, you can use the built-in next() function to generate the next value in the sequence.

For example:

# Generate squares from 1 to 10
squares = (x**2 for x in range(1, 11))

# Print the first five squares
for i in range(5):
    print(next(squares))

Output:

1
4
9
16
25

Notice that the squares are calculated on the fly rather than storing them in memory. Because of this, you could use a generator to generate squares all the way to infinity without running into memory problems.

2. What Is the tuple() Function in Python?

In Python, the tuple() function is used to create a tuple or to convert an iterable like list to tuple.

A tuple is a sequence of values that cannot be changed (immutable).

Tuples are similar to lists, but they are typically used for different purposes. While a list is used to store a collection of related items, a tuple is used to store a fixed number of items that may not be related.

Here is an example of creating a tuple from a list using the tuple() function:

# Create a tuple with three elements
my_tuple = tuple([1, 2, 3])

# Print the tuple
print(my_tuple)

Output:

(1, 2, 3)

The tuple() function takes a sequence (such as a list) as an argument and returns a tuple with the same elements. This can be useful if you want to convert another iterable like a list into a tuple.

3. tuple() + Generator Expression

Now that you have a basic understanding of what is a generator expression and tuple() function, you have the keys to understanding how the ‘tuple comprehension’ works.

Let’s take a look at the example in the intro:

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

# 'Tuple comprehension'
squares = tuple(x**2 for x in numbers)

print(squares)  # Output: (1, 4, 9, 16, 25)

Here the result of x**2 for x in numbers is a generator. It is like any other iterable in Python. You can iterate its elements or convert it to something else such as a list or tuple.

The tuple() function turns the generator into a tuple of values.

Don’t Use ‘Tuple Comprehensions’

Unless you don’t care about performance, you shouldn’t use tuple comprehensions.

If you need to create a tuple in a way that resembles a comprehension, the best way is to:

  1. Do a list comprehension.
  2. Convert the list to a tuple.

This gives the fastest results.

To verify this, let’s run a little performance competition by running different approaches to creating a tuple with comprehension. (Run these commands from the command line to repeat)

1. List comprehension

python3 -m timeit 'l = [i for i in range(1000)]'

Output:

20000 loops, best of 5: 13.6 usec per loop

2. Tuple from list comprehension

python3 -m timeit 'l = tuple([i for i in range(1000)])'

Output:

20000 loops, best of 5: 14.8 usec per loop

3. Tuple from generator

python3 -m timeit 'l = tuple(i for i in range(1000))'

Output:

10000 loops, best of 5: 20.7 usec per loop

4. Tuple from unpacking syntax

python3 -m timeit 'l = *(i for i in range(1000)),'

Output:

10000 loops, best of 5: 21.8 usec per loop

As you can see, the 2nd approach was the fastest.

In other words, to use a ‘tuple comprehension’ in Python, just create a list using list comprehension and create a tuple from the list by using the tuple() function.

Summary

Today you learned that tuple comprehensions don’t exist in Python. To mimic the behavior and get a syntactically similar outcome, use tuple() function with a generator expression.

Thanks for reading. Happy coding!

Read Also

Comprehensions in Python