Weird behavior in python list concatenation -
this question has answer here:
- why += behave unexpectedly on lists? 7 answers
i create python list as
>>> list1 = ['a', 'b', 'c'] and set
>>> list2 = list1 now perform 2 similar operations list1 , list2
>>> list1 = list1 + [1, 2, 3] >>> list1 ['a', 'b', 'c', 1, 2, 3] >>> list2 ['a', 'b', 'c'] and
>>> list2 += [1,2,3] >>> list1 ['a', 'b', 'c', 1, 2, 3] >>> list2 ['a', 'b', 'c', 1, 2, 3] but results different in both cases. reason it?
the += operator in python lists, internally calls list.extend() function, , hence list extended in place.
whereas when + concatenation operator , new list created , returned, hence actual list there in list1 not changed, instead list1 points new list.
Comments
Post a Comment