0

I am using a stack class to store 2d lists of strings and integers. The lists serve as tables and I have the following code:

print('pushing')
print(lookup_table)
tables_to_be_tested.push(lookup_table)
print('new table')
print(lookup_table)
print('top of stack: ')
print(tables_to_be_tested.peek())
lookup_table[0][c2index] = c1_value
print('top of stack 2: ')
print(tables_to_be_tested.peek())

The line lookup_table[0][c2index] = c1_value only updates one value in the first list

Here is my output:

pushing
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [39, 50, 38, 53, 28, 37, 49, 52, 31, 42], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
new table
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [39, 50, 38, 53, 28, 37, 49, 52, 31, 42], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
top of stack:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [39, 50, 38, 53, 28, 37, 49, 52, 31, 42], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
top of stack 2:
[[0, 1, 2, 3, 4, 10, 6, 7, 8, 9], [39, 50, 38, 53, 28, 37, 49, 52, 31, 42], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

The lists are created independently like this: lookup_table = [[],[],[]] and are appended to in a for loop. The calculation should not affect the 2d list in the stack and yet it does. Why is this? What is a solution?

  • 1
    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) – Pranav Hosangadi Feb 12 '21 at 18:55
  • @PranavHosangadi No because the lists are created like this: lookup_table = [[],[],[]] where each sublist is different unlike that solution where 3 copies of one list were made. – Cameron Fraser Feb 12 '21 at 19:01

0 Answers0