0

I understand that these two statements are same only syntactically but their implementation is different:

>>>    s = [1,2,3]
>>>    t = [4,5,6]  
>>>    s += t    
>>>    s = s + t

In the first case the left side is evaluated only once.

But how is that implemented ?

What is meant by evaluated only once?

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208
  • An interesting topic, and I'm reading corresponding PEP now: http://legacy.python.org/dev/peps/pep-0203/. In short, several hooks are introduced into python object for this feature. – mission.liao Aug 03 '15 at 03:50
  • has answer here: http://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python – Ozgur Vatansever Aug 03 '15 at 03:53

1 Answers1

1

In case of lists, += is in place, meaning it does not create a new list, it changes the list on the left side. It internally calls the __iadd__() method for list (where the i stands for in place) .

where as the concatenation operator + actually creates a new list. (It internally calls the __add__() method)

A simple example to show this difference -

For += -

>>> s = [1,2,3]
>>> t = [4,5,6]
>>> z = s
>>> s+=t
>>> s
[1, 2, 3, 4, 5, 6]
>>> z
[1, 2, 3, 4, 5, 6]

For concatenation -

>>> s = [1,2,3]
>>> t = [4,5,6]
>>> z = s
>>> s = s + t
>>> z
[1, 2, 3]
>>> s
[1, 2, 3, 4, 5, 6]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176