Python appends to all lists(like they are different pointer for the same memory address) when decalred with one line syntax(this: a = b = c []
) but no such case with non-iterables or seperate declaration.
Same thing was causing a bug in my program when I used append()
and after some(a lot) debugging I found that this was causing the bug.
Example code with output:
a = b = c = []
a.append(1)
b.append(2)
print("1st", a, b, c)
# Output: 1st [1, 2] [1, 2] [1, 2]
# But not with some other types or when reassigned
# Reassigning list
a = b = c = []
a = [1, 2, 3]
print("2nd", a, b, c)
# Output:2nd [1, 2, 3] [] []
# Multi-line for control
a = []
b = []
c = []
a.append(1)
b.apend(2)
print("3rd", a, b, c)
# Output:3rd [1] [2] []
Seperate output of program
Output:
1st [1, 2] [1, 2] [1, 2]
2nd [1, 2, 3] [] []
3rd [1] [2] []
Are the lists something like different references but to the same memory address when assigned with one line syntax.