Doubt: | SoloLearn: Learn to code for FREE!

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

5/22/2020 6:22:00 AM

Yogesh Kulkarni

3 Answers

New Answer

+4

List1=list1+[4] changes the Id of the list.

+2

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.

0

Thanks for your response , now I am clear :)