+ 2

Python - How come zzz[0] += [[]] is not the same as zzz[0]= zzz[0] + [[]] ?

I'm comparing two chunks of code: Case 1: zzz = [[]] *3 print(zzz) # outputs [[], [], []] zzz[0]= zzz[0] + [[]] print(zzz) # outputs [[[]], [], []] Case 2: zzz = [[]] *3 print(zzz) # outputs [[], [], []] zzz[0] += [[]] print(zzz) # outputs [[[]], [[]], [[]]] In the second case, why does zzz[0] += [[]] add a pair of square brackets in EACH item instead of just the first one?

10th Oct 2020, 8:08 PM
Solus
Solus - avatar
2 odpowiedzi
+ 10
The following link explains well about how list+=item and list=list+item works https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists when you do [[]]*3 it creates 3 list object pointing to same location ,so [][][] are all pointing to same location ,and change to anyone one of them will effect other as well In zzz[0]=zzz[0]+[[]], we are adding new item to the first list of zzz ,doing this way calls add method which creates a new list object so zzz[0] now is assigned a different list object ,and since this Operation created a new list object other two lists aren't affected at all But doing this zzz[0]+=[[]] calls iadd method which changes the original list data instead of creating a new object ,so you must know by now what will happen to other two list object ,since they all were pointing to same location you get output as [[[]],[[]],[[]]]
10th Oct 2020, 8:23 PM
Abhay
Abhay - avatar
+ 1
The + operator tries to call the __add__ dunder method. <-- Case 1 The += operator tries to call the __iadd__ dunder method. <-- Case 2 If __iadd__ is unavailable, __add__ is used instead. --> For mutable types like lists, the += changes the original object's value --> For immutable types like tuples/strings/integers, a NEW object is returned (ie. a += b becomes equivalent to a = a + b) In the case of zzz above, it is a mutable type with three objects pointing to same location.
10th Oct 2020, 11:37 PM
Solus
Solus - avatar