Appending two lists mutually to each other gives unexpected results containing "[...]"

97 Views Asked by At

I have 2 lists:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7]

I performed the following two operations and tried printing each list

a.append(b)
b.append(a)
print(a) # Expected Result: [1, 2, 3, 4, 5, [9, 8, 7]]
print(b) # Expected Result: [9, 8, 7, [1, 2, 3, 4, 5]]

But the result turned out to be:

a = [1, 2, 3, 4, 5, [9, 8, 7, [...]]]
b = [9, 8, 7, [1, 2, 3, 4, 5, [...]]]

Can someone explain in detail what exactly is happening here?

I tried printing each element of the list but the list keep on going without any end.

3

There are 3 best solutions below

0
matszwecja On BEST ANSWER

Python lists are stored by references. You add such reference to the lists, which can be still modified in another place. After a.append(b) you've got [1, 2, 3, 4, 5, b]. That b has value [9,8,7] at the moment, but when you b.append(a), you change the value of it to [9, 8, 7, a]. And that a happens to contain b, and so on ending up with cycle of two lists contained in each other. If you want to avoid that, you need to make a copy of list you want to append. A copy will make it so changes to original list are not reflected in the copy.

a = [1,2,3,4,5]
b = [9,8,7]

a_copy = a.copy()
b_copy = b.copy()

a.append(b_copy)
b.append(a_copy)

print(a) # Expected Result: [1,2,3,4,5,[9,8,7]]
print(b) # Expected Result: [9, 8, 7 ,[1,2,3,4,5]]
0
user64bit On

This is happening because when you append one list to another, you are not creating a copy of the list, but rather adding a reference to the original list. This means that if you modify the original list, the changes will be reflected in the appended list as well, and vice versa.

You create a circular reference where list a contains a reference to list b, and list b contains a reference to list a. This is why when you print the lists, you see nested lists

if you try using a.copy() and b.copy() then you'll get your desired output.

0
Guy On

You can also create both lists in the same time. This will create two new lists when both are evaluated before the assignment

a, b = a + [b], b + [a]

# [1, 2, 3, 4, 5, [9, 8, 7]]
# [9, 8, 7, [1, 2, 3, 4, 5]]