Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Under the covers, <code>i += 1</code> does something like this:</p> <pre><code>try: i = i.__iadd__(1) except AttributeError: i = i.__add__(1) </code></pre> <p>While <code>i = i + 1</code> does something like this:</p> <pre><code>i = i.__add__(1) </code></pre> <p>This is a slight oversimplification, but you get the idea: Python gives types a way to handle <code>+=</code> specially, by creating an <code>__iadd__</code> method as well as an <code>__add__</code>.</p> <p>The intention is that mutable types, like <code>list</code>, will mutate themselves in <code>__iadd__</code> (and then return <code>self</code>, unless you're doing something very tricky), while immutable types, like <code>int</code>, will just not implement it.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; l1 = [] &gt;&gt;&gt; l2 = l1 &gt;&gt;&gt; l1 += [3] &gt;&gt;&gt; l2 [3] </code></pre> <p>Because <code>l2</code> is the same object as <code>l1</code>, and you mutated <code>l1</code>, you also mutated <code>l2</code>.</p> <p>But:</p> <pre><code>&gt;&gt;&gt; l1 = [] &gt;&gt;&gt; l2 = l1 &gt;&gt;&gt; l1 = l1 + [3] &gt;&gt;&gt; l2 [] </code></pre> <p>Here, you didn't mutate <code>l1</code>; instead, you created a new list, <code>l1 + [3]</code>, and rebound the name <code>l1</code> to point at it, leaving <code>l2</code> pointing at the original list.</p> <p>(In the <code>+=</code> version, you were also rebinding <code>l1</code>, it's just that in that case you were rebinding it to the same <code>list</code> it was already bound to, so you can usually ignore that part.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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