Can someone explain this expression: a[len(a):] = [x] equivalent to list.append(x)
<p>I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:</p>

<pre><code>list.append(x)
</code></pre>

<p>and in the tutorial it is said to be equivalent to this expression:</p>

<pre><code>a[len(a):] = [x]
</code></pre>

<p>Can someone please explain this expression? I can't grasp the <strong>len(a):</strong> part. It's a slice right? From the last item to the last? Can't make sense of it.</p>

<p>I'm aware this is very newbie, sorry. I'm determined to learn Python for Blender scripting and the Game Engine, and want to understand well all the constructs.</p>

<p>One could generally state that <code>l[len(l):] = [1]</code> is similar to <code>append</code>, <em><a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">and that is what is stated in the docs</a></em>, but, that is a <em>special case</em> that holds true only when the right hand side <em>has a single element</em>. </p>

<p>In the more <em>general case</em> it is safer to state that it is equivalent to <code>extend</code> for the following reasons:</p>

<p>Append takes an <em>object</em> and appends that to the end; with slice assignment you <strong>extend</strong> a list with the given iterable on the right hand side:</p>

<pre><code>l[len(l):] = [1, 2, 3]
</code></pre>

<p>is equivalent to:</p>

<pre><code>l.extend([1, 2, 3])
</code></pre>

<p>The same argument to <code>append</code> would cause <code>[1, 2, 3]</code> to be appended as  an object at the end of <code>l</code>. In this scenario <code>len(l)</code> is simply used in order for the extending of the list to be performed at the end of <code>l</code>.</p>

<p>Some examples to illustrate their difference:</p>

<pre><code>l = [1, 2]
l[len(l):] = [1, 2]   # l becomes [1, 2, 1, 2]
l.extend([1, 2])      # l becomes [1, 2, 1, 2, 1, 2]
l.append([1, 2])      # l becomes [1, 2, 1, 2, 1, 2, [1, 2]]
</code></pre>

<p>As you note, <code>l.append(&lt;iterable&gt;)</code> doesn't actually append each value in the iterable, it appends the iterable itself.</p>

python list python-3.x