Tuple comprehension in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Check out my new book

Tuple comprehension in Python #

There is no tuple comprehension in Python, but you can get the desired result by using a generator expression and converting the generator object to a tuple, e.g. my_tuple = tuple(int(element) for element in ('1', '3', '5')).

main.py
my_tuple = tuple( int(element) for element in ('1', '3', '5') ) print(my_tuple) # 👉️ (1, 3, 5)

We used a generator expression and converted the result to a tuple using the tuple() class.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

Had we not used the tuple() class, we would get a generator object.

main.py
my_generator = ( int(element) for element in ('1', '3', '5') ) # 👇️ <generator object <genexpr> at 0x7f67b525c660> print(my_generator)

We could have also wrapped a list comprehension in the tuple() class to simulate a tuple comprehension.

main.py
my_tuple = tuple( [element + 10 for element in (1, 3, 5)] ) print(my_tuple) # 👉️ (11, 13, 15)

Had we not used the tuple() class, we would get a list object.

main.py
my_list = [element + 10 for element in (1, 3, 5)] print(my_list) # 👉️ [11, 13, 15]
Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

Using the tuple() class with a generator expression or a list comprehension is useful when:

  • we need an immutable data structure because the contents of a variable won't change
  • we need a hashable object that can be used as a key in a dictionary

Tuples can be used as a key in a dictionary or as an element in a set because they are immutable and hashable.

Whereas lists cannot because they are mutable and unhashable.

If an object is hashable, then it can be used as a key in a dictionary and as an element in a set, because these data structures use the hash value internally

Hashable objects include - str, int, bool, tuple, frozenset.

Unhashable objects include - list, dict, set.

Note that tuples and frozensets are only hashable if their elements are hashable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.