0

I've got python where an assignment to a specific 2d list in python is updating multiple elements and I don't know why. I'm not looking for a better way to do things as much as I'm trying to understand what is going on here so I get my mistake before just doing something else. Below is the code and beneath it snippet of what gets printed out after a couple loops. Notice that with each assignment to an index, the tuple being assigned to that index is written to multiple locations in the 2d list. I don't even know how that is possible.

num_list = []
for num in range(32, 43, 1):
    num_list.append((str(num), chr(num) + " "))
print
print "num_list:"
print num_list
print

cols = 4
rows = len(num_list) / cols

arry2d = [[("a","b")] * cols] * (rows+1)
print ("arry2d after initialization")
print arry2d
print


for i, item in enumerate(num_list):
        print "i: " + str(i),
        print "row: ", i / cols,
        print "column: ", i % cols,
        print "contents before update: ", arry2d[i / cols][i % cols]
        print "item: ", item
        print "array 2d after update with item: ", item
        arry2d[i / cols][i % cols] = item
        print arry2d
----------------------------------------------------

Output

num_list
[('32', '  '), ('33', '! '), ('34', '" '), ('35', '# '), ('36', '$ '), ('37', '% '), ('38', '& '), ('39', "' "), ('40', '( '), ('41', ') '), ('42', '* ')]

arry2d after initialization
[[('a', 'b'), ('a', 'b'), ('a', 'b'), ('a', 'b')], [('a', 'b'), ('a', 'b'), ('a', 'b'), ('a', 'b')], [('a', 'b'), ('a', 'b'), ('a', 'b'), ('a', 'b')]]

i: 0 row:  0 column:  0 contents before update:  ('a', 'b')
item:  ('32', '  ')
array 2d after update with item:  ('32', '  ')
[[('32', '  '), ('a', 'b'), ('a', 'b'), ('a', 'b')], [('32', '  '), ('a', 'b'), ('a', 'b'), ('a', 'b')], [('32', '  '), ('a', 'b'), ('a', 'b'), ('a', 'b')]]
i: 1 row:  0 column:  1 contents before update:  ('a', 'b')
item:  ('33', '! ')
array 2d after update with item:  ('33', '! ')
[[('32', '  '), ('33', '! '), ('a', 'b'), ('a', 'b')], [('32', '  '), ('33', '! '), ('a', 'b'), ('a', 'b')], [('32', '  '), ('33', '! '), ('a', 'b'), ('a', 'b')]]
Kenan
  • 13,156
  • 8
  • 43
  • 50
wdog
  • 5
  • 4
  • 1
    `arry2d = [[("a","b")] * cols] * (rows+1)` Using `*` to initialize a list means you get multiple references to _the same object_. Updating one of them updates them all, because they're all _the same object_. – John Gordon Jan 30 '20 at 22:17
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Nathan Jan 30 '20 at 22:19

0 Answers0