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.

2
  • Apart from the empty tuple (), it is the comma that defines a tuple, not the parentheses that might surround the tuple literal. Commented Apr 2, 2018 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,) Commented Apr 2, 2018 at 17:40

2 Answers 2

4

Use the tuple() constructor:

x = tuple(i for i in range(5))
assert x == (0,1,2,3,4)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.