+ 6

What happens when we append an empty list to itself in python ?

code example : a=[] a.append(a) print(a) #prints [[...]]

2nd Apr 2021, 11:36 PM
Kareem Aladawy
Kareem Aladawy - avatar
5 Réponses
+ 4
Kareem Aladawy You're appending the same list to itself. This creates a recursive infinite nested reference binding. This is why you are getting [[...]] instead of [[]] If you use my example and after the print statement add l2.append(42) print(l2) # [42] print(l1) # [[42]] You will see That the reference to l2 within l1 will also change the nested list in l1 whenever you make changes to l2 by itself. A way you can prevent this from happening is to create a copy of the object and instead append that copy. a = [] a.append(a.copy()) print(a) Note: copy() makes a shallow copy of the list. If you also want new copies for the object elements of the list then you will need to make a deep copy. deepcopy()
3rd Apr 2021, 7:12 PM
ChaoticDawg
ChaoticDawg - avatar
+ 5
The appended empty list is added as an element to the previously empty list. The previously empty list is now a list with 1 element that is itself an empty list. The result is; [[]] l1 = [] l2 = [] l1.append(l2) # l2 is added as an element to l1 print(l1) # outputs [[]]
3rd Apr 2021, 12:31 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
ChaoticDawg thank you, just what I needed
3rd Apr 2021, 7:16 PM
Kareem Aladawy
Kareem Aladawy - avatar
+ 3
Simply a empty list will the another empty list so now the list which was empty earlier in which you are appending another empty list will not be empty now because it have 1 element now . Which is a empty list
3rd Apr 2021, 3:44 AM
Ayush Kumar
Ayush Kumar - avatar
+ 3
Please consider looking at the code example
3rd Apr 2021, 8:33 AM
Kareem Aladawy
Kareem Aladawy - avatar