Altering One Python List In Dictionary Of Lists Alters All Lists
Possible Duplicate: Two separate python lists acting as one This code creates a dictionary of lists, the keys being in usens. The lists are full of 0s usens = [0, 1, 2, 3, 4, 5,
Solution 1:
empty = [[0]*length]*len(usens) will create len(usens) copies of the same list, which is different from len(usens) lists with the same content.
Try empty = [[0]*length for i in range(len(usens))].
Solution 2:
Using * creates copies; for [0] it's fine, because it's copying an immutable scalar; but the outer * creates copies of the same list (i.e., copies a reference). You could use something like:
empty = [0]*5data = {n:list(empty) for n in usens}
(a dict comprehension) to create your list (if using Python 2.7+). Using list makes a copy.
Post a Comment for "Altering One Python List In Dictionary Of Lists Alters All Lists"