I wanted to understand what's going on in the system memory for it to give the following outputs for the following lines of code.
list_1 = [1, 2, 3]
list_2 = list_1
list_1 = list_1 + [4]
print(list_1)
print(list_2)
For this, the output of list_1 is a list of 1, 2, 3 and 4. Whereas the output of list_2 is a list of 1, 2 and 3. This all makes sense so far.
list_1 = [1, 2, 3]
list_2 = list_1
list_1.append(4)
print(list_1)
print(list_2)
For this one both list_1 and list_2 have an output of a list of 1, 2, 3 and 4 which also makes sense as list_2 points to list_1 and with the append method the number 4 gets added to the end of list_1.
list_1 = [1,2,3]
list_2 = list_1
list_1 += [4]
print(list_1)
print(list_2)
For this above code, the output is a list of 1, 2, 3 and 4 for both list_1 and list_2 which is not what I expected. Shouldn't using the list_1 += [4] yield the same output as using list_1 = list_1 + [4]? But that is not what is happening according to the outputs I got. Anyone knows why and can enlighten me on this?