Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Python distinguishes between the <code>+</code> and <code>+=</code> operators and provides separate hooks for these; <a href="http://docs.python.org/2/reference/datamodel.html#object.__add__" rel="noreferrer"><code>__add__</code></a> and <a href="http://docs.python.org/2/reference/datamodel.html#object.__iadd__" rel="noreferrer"><code>__iadd__</code></a>. The <code>list()</code> type simply provides a different implementation for the latter.</p> <p>It is more efficient for lists to implement these separately; <code>__add__</code> has to return a completely new list, while <code>__iadd__</code> can just extend <code>self</code> then return <code>self</code>.</p> <p>In the C code, <code>__iadd__</code> is implemented by <a href="http://hg.python.org/cpython/file/b0935ef48186/Objects/listobject.c#l914" rel="noreferrer"><code>list_inplace_concat()</code></a>, which simply calls <code>listextend()</code>, or, in python code, <code>[].extend()</code>. The latter takes <em>any</em> sequence, by design.</p> <p>The <code>__add__</code> method on the other hand, represented in C by <a href="http://hg.python.org/cpython/file/b0935ef48186/Objects/listobject.c#l506" rel="noreferrer"><code>list_concat</code></a>, only takes a <code>list</code> as input, probably for efficiency's sake; it can loop directly over the internal C array and copy items over to the new list.</p> <p>In conclusion, the reason <code>__iadd__</code> accepts any sequence is because when <a href="http://www.python.org/dev/peps/pep-0203/" rel="noreferrer">PEP 203</a> (the Augmented Add proposal) was implemented, for lists it was simplest just to reuse the <code>.extend()</code> method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload