Python : how to append new elements in a list of list? -
here simple program:
= [[]]*3 print str(a) a[0].append(1) a[1].append(2) a[2].append(3) print str(a[0]) print str(a[1]) print str(a[2]) here output expecting:
[[], [], []] [1] [2] [3] but instead :
[[], [], []] [1, 2, 3] [1, 2, 3] [1, 2, 3] there not here !
you must do
a = [[] in xrange(3)] not
a = [[]]*3 now works:
$ cat /tmp/3.py = [[] in xrange(3)] print str(a) a[0].append(1) a[1].append(2) a[2].append(3) print str(a[0]) print str(a[1]) print str(a[2]) $ python /tmp/3.py [[], [], []] [1] [2] [3] when a = [[]]*3 same list [] 3 times in list. the same means when change 1 of them change of them (because there 1 list referenced 3 times).
you need create 3 independent lists circumvent problem. , list comprehension. construct here list consists of independent empty lists []. new empty list created each iteration on xrange(3) (the difference between range , xrange not important in case; xrange little bit better because not produce full list of numbers , returns iterator object instead).
Comments
Post a Comment