As we all know, there's list comprehension, like
[i for i in [1, 2, 3, 4]]
and there is dictionary comprehension, like
{i:j for i, j in {1: 'a', 2: 'b'}.items()}
but
(i for i in (1, 2, 3))
will end up in a generator, not a tuple
comprehension. Why is that?
My guess is that a tuple
is immutable, but this does not seem to be the answer.
We can perform comprehension to sequences such as lists, sets, dictionaries but not to tuples.
the choice between tuple or list is based on what you are planning on doing with it and not resources. Apart from the overhead of the conversion, the tuple will be smaller and faster, since it lacks the mechanism to make it mutable, allow fast inserts etc.
The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
The Python tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an ordered and immutable sequence type.
You can use a generator expression:
tuple(i for i in (1, 2, 3))
but parentheses were already taken for … generator expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With