Two 'identical' nested lists don't seem to function the same way

I make two nested lists (map_list and map_list2), one by using loops to create it, one by just making it directly. They seem identical because map_list == map_list2 returns True. However, when I try to make a change to the lists (i.e. map_list[0][0] = 1) they seem to react differently. What gives :D?

map_list = [] column_list = [] for i in range(3): column_list.append(0) for i in range(3): map_list.append(column_list) map_list2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] #returns True print(map_list2 == map_list) #returns [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print(map_list) map_list[0][0] = 1 #returns [[1, 0, 0], [1, 0, 0], [1, 0, 0] print(map_list) print() map_list2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] #returns [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print(map_list2) map_list2[0][0] = 1 #returns [[1, 0, 0], [0, 0, 0], [0, 0, 0]] print(map_list2)
map_list.append(column_list)

You are creating what looks like three lists but in fact is only one list, referenced three times. A change in one will reflect in all three lists.

2 Likes

Thanks. Started reading up on deep vs shallow copies. Spent 2 hours trying to find where I’d written something incorrectly for my advent of code program… A lesson I won’t be forgetting soon.

1 Like