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.
My best guess is that they ran out of brackets and didn't think it would be useful enough to warrent adding an "ugly" syntax ...
Parentheses do not create a tuple. aka one = (two) is not a tuple. The only way around is either one = (two,) or one = tuple(two). So a solution is:
Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.
Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). Because the Tuple is only holding a reference to that kind of object.
Also - a tuple has its own constructor
tuple()
which you can give any iterator. Which means that to create a tuple, you could do:Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet:
This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. Although a tuple is iterable and seems like simply a immutable list, it's really the Python equivalent of a C struct:
becomes in Python
We can generate tuples from a list comprehension. The following one adds two numbers sequentially into a tuple and gives a list from numbers 0-9.
Since Python 3.5, you can also use splat
*
unpacking syntax to unpack a generator expresion: