2

How can I create a tuple using a for in loop in python? I tried running the following:

>>> x = (i for i in range(15))
>>> x
<generator object <genexpr> at 0x00000198CAC95A40>

But this gives a generator object instead of a tuple. Any ideas on how to get this? Not just needed to get the sequence of ints from 0 to 14 but other operations as well.

ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • Apart from the empty tuple `()`, it is the *comma* that defines a tuple, not the parentheses that might surround the tuple literal. – chepner Apr 02 '18 at 17:37
  • @chepner Yeah! I forgot about that. Parenthesis are also for expressions and in this case it's being treated like a statement. I now remember I had read about this some time ago when finding how to create a single element tuple. Like: `(1,)` – ayushgp Apr 02 '18 at 17:40

2 Answers2

4

Use the tuple() constructor:

x = tuple(i for i in range(5))
assert x == (0,1,2,3,4)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
3

You don't actually need the generator here at all; tuple(range(5)) will work.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895