Skip to content

Tuple comprehension Python | Example code

  • by

There is no tuple comprehension in Python. Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

List comprehension

[i for i in [1, 2, 3, 4]]

Dictionary comprehension

i:j for i, j in {1: 'a', 2: 'b'}.items()}

For tuple use generator expression:

tuple(i for i in (1, 2, 3))

Example tuple comprehension Python

Simple example code. Wrap generator object using tuple() function.

tuple1 = (1, 6, 5, 9, 9, 1, 25, 76)
tuple2 = tuple((i for i in tuple1 if i % 5 == 0))

print(tuple2)

Output:

Tuple comprehension Python

What is comprehension in Python?

In python, comprehension is a technique with the help of which we can create sequences of elements in a short, concise manner.

Do comment if you have any doubts and suggestions on this Python tuple topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *