21

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.

0

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually there is tuple comprehension: xs = [1, 2, 3]; ys = tuple(x for x in xs); type(ys)
@visitor That's not a tuple comprehension. x for x in xs is a generator, and this is then converted to a tuple.
7

Parentheses are used for three different things: grouping, tuple literals, and function calls. Compare (1 + 2) (an integer) and (1, 2) (a tuple). In the generator assignment, the parentheses are for grouping; in the tuple assignment, the parentheses are a tuple literal. Parentheses represent a tuple literal when they contain a comma and are not used for a function call.

2 Comments

I under (1+2) is int and (1, 2) would be function call, what i don't understand is what you mean by in the generator assignment.
@GaurangShah: When you’re assigning generator = …. … for … in … is a generator when it’s inside parentheses.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.