It's possible to use the following code to create a list:
>>> [i+1 for i in(0,1,2)]
[1, 2, 3]
Can a similar thing be done with tuples?
>>> (i+1 for i in(0,1,2)),
(<generator object <genexpr> at 0x03A53CF0>,)
I would have expected (1, 2, 3)
as the output.
I know you can do tuple(i+1 for i in(0,1,2))
, but since you can do [i+1 for i in(0,1,2)]
, I would expect a similar thing to be possible with tuples.
Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.
You can imagine tuples as being created when you hardcode the values, while generators are created where you provide a way to create the objects. This works since there is no way (1,2,3,4) could be a generator. There is nothing to generate there, you just specified all the elements, not a rule to obtain them.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
In python 3 you can unpack a generator using *
.
Here is an example:
>>> *(i+1 for i in (1,2,3)),
(2, 3, 4)
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