7

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.

Programmer S
  • 411
  • 5
  • 19

1 Answers1

22

In python 3 you can unpack a generator using *.

Here is an example:

>>> *(i+1 for i in (1,2,3)),
(2, 3, 4)
Programmer S
  • 411
  • 5
  • 19
Sunitha
  • 11,422
  • 2
  • 17
  • 22
  • 3
    It's a cool trick but it's not explicit enough, and propably does not have the speed of a comprehension. – Guimoute May 17 '20 at 17:47
  • 4
    It __is__ a trick and a little less readable. I missed the `,` at the end when I tried it for the first time. – migrant Jan 14 '21 at 18:02
  • Do not be mistaken, this method is **not** faster than the obvious one: `tuple(i+1 for i in (1,2,3))`. It is just less readable and more confusing. --- It is also not some special syntax it is just unpacking the generator (it temporarily creates a list from it) into a new tuple (marked by the trailing coma). – pabouk - Ukraine stay strong May 29 '22 at 16:21