Weird behavior in python list concatenation -


this question has answer here:

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

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -