+ 6
What happens when we append an empty list to itself in python ?
code example : a=[] a.append(a) print(a) #prints [[...]]
5 Respostas
+ 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()
+ 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 [[]]
+ 4
ChaoticDawg thank you, just what I needed
+ 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
+ 3
Please consider looking at the code example