python - Forcing a list out of a generator -
>>>def change(x): ... x.append(len(x)) ... return x >>>a=[] >>>b=(change(a) in range(3)) >>>next(b) [0] >>>next(b) [0,1] >>>next(b) [0,1,2] >>>next(b) traceback ... stopiteration >>>a=[] >>>b=(change(a) in range(3)) >>>list(b) #expecting [[0],[0,1],[0,1,2]] [[0,1,2],[0,1,2],[0,1,2]]
so testing understanding of generators , messing around command prompt , i'm unsure if understand how generators work.
the problem calls change(a)
return the same object (in case, object value of a
), object mutable , changes value. example of same problem without using generators:
a = [] b = [] in range(3): a.append(len(a)) b.append(a) print b
if want avoid it, need make copy of object (for example, make change
return x[:]
instead of x
).
Comments
Post a Comment