I have following code:
# python 3.8
normtable = [[None, None],[None, None],[None, None]]
calctable = [[None]*2]*3
print('Before update - Normaltable: \t\t'+ str(normtable))
print('Before update - Calculatedtable: \t'+ str(calctable))
normtable[0][0] = 'hello'
calctable[0][0] = 'hello'
print('After update - Normaltable: \t\t'+ str(normtable))
print('After update - Calculatedtable: \t'+ str(calctable))
Output is like this:
Before update - Normaltable: [[None, None], [None, None], [None, None]]
Before update - Calculatedtable: [[None, None], [None, None], [None, None]]
After update - Normaltable: [['hello', None], [None, None], [None, None]]
After update - Calculatedtable: [['hello', None], ['hello', None], ['hello', None]]
Why does the calculated list behave differently?
I understand that lists are mutable and thus if the same list is used in another list and the second list edited the first one is also edited as both point to the same values.
This explains, why that after multiplying the same list with factor 3 all three lists will always contain the same information. But then why would the *2 not do the same and as a result all strings change to 'hello' and not just the first ones?
What would be an alternative way to have this list set up with a variable size?
Thanks in advance, best answer will be marked.