YellowPillow
YellowPillow

Reputation: 4270

Python: Appending a function that yields to a list?

Hello and thanks for looking at my question! I was recently introduced to generators and I read the about on 'The Python yield keyword explained'. From my understanding, yield is generated on the fly, cannot be indexed and will remember where it left off after the yield command has been executed (correct me if I'm wrong I'm still new to this).

My question is then why does:

from itertools import combinations

x = [['4A'],['5A','5B','5C'],['7A','7B']]

y = list()

for combination in x:
    for i in range(1,len(combination)+1):
        y.append(list(combinations(combination,i)))
print y # [[('4A',)], [('5A',), ('5B',), ('5C',)], 
        # [('5A', '5B'), ('5A', '5C'), ('5B', '5C')], 
        # [('5A', '5B', '5C')], [('7A',), ('7B',)], [('7A', '7B')]]

But this doesn't work:

from itertools import combinations

x = [['4A'],['5A','5B','5C'],['7A','7B']]

y = list()

for combination in x:
    for i in range(1,len(combination)+1):
        y.append((combinations(combination,i)))
print y

Since I am appending the combinations to y straight after it is yielded why is it that when it is appended in a list form it works, but when I do it normally, it doesn't?

Upvotes: 1

Views: 771

Answers (1)

dano
dano

Reputation: 94921

When you call list(generator_function()), generator_function is iterated to exhaustion, and each element is stored in a list. So, these three operations are doing the same thing:

l = list(generator_function())
...
l = [x for x in generator_function()]
...
l = []
for x in generator_function():
    l.append(x)

In your example, without including list(..), you're just appending the combinations generator object to the y. With list(...), you're iterating over the combinations generator to build a list object, and then appending that to y.

Upvotes: 3

Related Questions