Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tuple vs generator

I am having a problem understanding why one of the following line returns generator and another tuple.

How exactly and why a generator is created in the second line, while in the third one a tuple is produced?

sample_list = [1, 2, 3, 4]
generator = (i for i in sample_list)
tuple_ = (1, 2, 3, 4)

print type(generator)
<type 'generator'>

print type(tuple_)
<type 'tuple'>    

Is it because tuple is immutable object and when I try to unpack list inside (), it can't create the tuple as it has to change the tuple tuple.

like image 944
Gaurang Shah Avatar asked Aug 23 '17 20:08

Gaurang Shah


People also ask

Is tuple a generator in Python?

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.

Is tuple comprehension called generator?

Here, the asterisk symbolizes the tuple() function. Not using the asterisk and only using the trailing comma will create a tuple. But the contents of that tuple would be the generator object.

Why tuple comprehension is not possible in Python?

There is no tuple comprehension in Python. Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

Is tuple comprehension faster than list comprehension?

the choice between tuple or list is based on what you are planning on doing with it and not resources. Apart from the overhead of the conversion, the tuple will be smaller and faster, since it lacks the mechanism to make it mutable, allow fast inserts etc.


1 Answers

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.

In order for your generator to be a tuple, the expression (i for i in sample_list) would have to be a tuple comprehension. There is no way to have tuple comprehensions, since comprehensions require a mutable data type.

Thus, the syntax for what should have been a tuple comprehension has been reused for generators.

like image 136
Paul92 Avatar answered Oct 29 '22 01:10

Paul92