Tom Zheng
Tom Zheng

Reputation: 41

Why does this python generator act like this?

def upto(n):
    items = []
    for i in range(n):
        items.append(i)
        yield items

print(list(upto(2)))

Why is the print output [[0,1],[0,1]]? When I call next on upto(2) twice, it yields [0] the first time and [0,1] the second time, so shouldn't the result be [[0], [0,1]]?

Upvotes: 4

Views: 80

Answers (3)

Md Mahmood Bin Habib
Md Mahmood Bin Habib

Reputation: 71

The thing is,you are referencing the same list(list work by reference) when trying to call list method on a generator. the list you are yielding is updated each time you loop through.so when you list up the generator it gets the updated one. for getting what you want you could do one of the following two things,

  1. yield a new list every time you loop through, like yield items[:]
  2. iterate through the returned generator, like for i in upto(2): print(i) # here,each time it gets the current one

Upvotes: 0

B. Kanani
B. Kanani

Reputation: 646

In [1]:

def upto(n):
    items = []
    for i in range(n):
        items.append(i)
        yield items.copy()

list(upto(2))

Out[1]: [[0], [0, 1]]

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113978

you need to yield a copy try yield items[:]

Upvotes: 2

Related Questions