python - Incorrect List manipulation -
let's
>>> = [1,2,3,4,5] and want output like
>>> b [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] here code:
class child(object): def get_lines(self): = [1,2,3,4,5] b=[] c=[] j=0 in a: print b.append(i) print b c.insert(j,b) j=j+1 print c son= child() son.get_lines() when print list b in loop, gives:
1 [1] 2 [1, 2] 3 [1, 2, 3] 4 [1, 2, 3, 4] 5 [1, 2, 3, 4, 5] and output is:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] where make wrong in code?
b always same list object (note i've changed print c return c):
>>> map(id, child().get_lines()) ... [49021616, 49021616, 49021616, 49021616, 49021616] c contains 5 references same list. think want is:
class child(object): def get_lines(self): = [1, 2, 3, 4, 5] return [a[:x+1] x in range(len(a))] this makes shallow copy of part (or all) of a each step:
>>> child().get_lines() [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Comments
Post a Comment