0

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?

Solid
  • 1
  • 1
  • Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Sep 16 '22 at 08:13
  • In general, `+` & `+=` are not equivalent for objects. They are governed by different methods: `__add__` & `__iadd__` respectively. So they might differ in their behaviour. – rdas Sep 16 '22 at 08:13
  • When you do list1 = list1+[4] The concatenate operation is used to merge two lists and return a single list. The + sign is used to perform the concatenation. Note that the individual lists are not modified, and a new combined list is returned. While when using += you are modifying the original list, hence your odd result! – bylal Sep 16 '22 at 08:15
  • "Concatenate" joins two specific items together, whereas "append" adds items at the end of data structure which support “append”.”append” is faster than “concatenation”. Python may create “new object” while doing “concatenation” while there is no new “object” created while “appending”. – Arya Singh Sep 16 '22 at 08:17
  • [`object.__iadd__`](https://docs.python.org/3/reference/datamodel.html#object.__iadd__) – Mechanic Pig Sep 16 '22 at 08:44

0 Answers0