Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I turn a generator object into a tuple without using "tuple()"? [duplicate]

Tags:

python

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.

like image 699
Programmer S Avatar asked Aug 12 '18 17:08

Programmer S


People also ask

How do you turn an object into a tuple?

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.

Is tuple a generator object?

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.

Can tuples be modified after creation?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.


1 Answers

In python 3 you can unpack a generator using *.

Here is an example:

>>> *(i+1 for i in (1,2,3)),
(2, 3, 4)
like image 86
Sunitha Avatar answered Oct 28 '22 13:10

Sunitha