Doubt: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Doubt:

In list operations, list1 is same as list2 in first code . Even after list1.append. But in second code, I appended list1 with different code, then list1 is not same as list2 Why ?I mean in both codes list2 was assigned with list1 value before the modification in list1 attributes #Code 1 list1 = [1,2,3] list2 =list1 list1.append(4) If list1== list2: print("It's same") #this gets printed #Code2 list1 = [1,2,3] list2 = list1 list1 = list1 + [4] If list1 == list2: print("it's same") #this is not executed

22nd May 2020, 6:22 AM
Yogesh Kulkarni
Yogesh Kulkarni - avatar
3 Answers
+ 5
In a little more detail, the __add__ special method defined for lists returns a new list object when called. This is invoked when using the addition operator on the list. On the other hand, if you do list1 += [4] += should invoke the __iadd__ special method, which instead does in-place addition without returning a new object.
22nd May 2020, 6:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
List1=list1+[4] changes the Id of the list.
22nd May 2020, 6:32 AM
Oma Falk
Oma Falk - avatar
0
Thanks for your response , now I am clear :)
22nd May 2020, 7:09 AM
Yogesh Kulkarni
Yogesh Kulkarni - avatar