pythonlistappendrecursive-datastructures

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


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.


Solution

  • 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]]