![]() |
VOOZH | about |
Python supports list, set, and dictionary comprehensions, but it does not have a dedicated tuple comprehension syntax. Instead, tuples can be created efficiently using generator expressions and the tuple() constructor.
List Comprehensions: These are used for creating new lists where each element is the result of some operation applied to each member of another sequence or iterable, or to satisfy a specific condition.
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehensions: We can use dictionary comprehension to directly create dictionaries from key-value pairs generated by running a loop over an iterable.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Set Comprehensions: Similar to list comprehensions, we can use set comprehension to create a collection of elements.
{16, 1, 4, 9}
If we want to create tuples using the idea of comprehension. We can follow a different approach. We can typecast the result of list, set, and dictionary comprehensions.
Converting a Generator to a Tuple: A generator expression can be converted into a tuple by passing it to the tuple() constructor:
(0, 2, 4, 6, 8)
Here, the generator expression is converted to a tuple by the tuple() constructor.
Lists, sets, and dictionaries to Tuple:
We can use a similar approach to get a tuple out of comprehension.
tuple_from_list_comprehension: (0, 2, 4, 6, 8) tuple_from_set_comprehension: (2, 3, 4, 5, 6) tuple_from_dict_comprehension: (0, 1, 2, 3, 4)
The above methods mimic the functionality of a tuple comprehension by using the flexibility of list, set, and dictionary comprehensions.
Note: When converting a dictionary to a tuple, we get a tuple of keys.