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

how to do line continuation in perl debugger for entering raw multi-line text (EOT)? -

javascript - Create websocket without connecting -

sharepoint - Accessing files across a shared directory using a Windows service -