9

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
  • 429
  • 7
  • 21

1 Answers1

24

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
  • 429
  • 7
  • 21
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • 4
    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
  • 7
    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
  • 2
    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
  • @pabouk-Ukrainestaystrong, doesn't this method at least skip the call to `tuple`? How do you know it is not faster? – Alexey Jun 24 '23 at 12:20