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.
As another poster
macm
mentioned , the fastest way to create a tuple from a generator istuple([generator])
.Performance Comparison
List comprehension:
Tuple from list comprehension:
Tuple from generator:
Tuple from unpacking:
My version of python:
So you should always create a tuple from a list comprehension unless performance is not an issue.
You can use a generator expression:
but parentheses were already taken for.. generator expressions.
I believe it's simply for the sake of clarity, we do not want to clutter the language with too many different symbols. Also a
tuple
comprehension is never necessary, a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension.Tuples cannot efficiently be appended like a list.
So a tuple comprehension would need to use a list internally and then convert to a tuple.
That would be the same as what you do now : tuple( [ comprehension ] )