python array inclusive slice index
<p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p>

<p>This would be possible if there is a syntax for slicing with inclusive end index. </p>

<pre><code>arr=[0,1,2,3,4,5]
for i in range(0,3):
    print arr[:-i]
</code></pre>

<p>output: </p>

<pre><code>[]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
</code></pre>

<p>wanted output: </p>

<pre><code>[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
</code></pre>

<p>The awkwardness arises from trying to take advantage of the <code>:-n</code> syntax.  Since there's no difference between <code>:0</code> and <code>:-0</code>, we can't use this syntax to distinguish <code>0 from the start</code> from <code>0 from the end</code>.</p>

<p>In this case it is clearer to use the <code>:i</code> indexing, and adjust the <code>range</code> accordingly:</p>

<pre><code>In [307]: for i in range(len(arr),0,-1): print(arr[:i])
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2]
[0, 1]
[0]
</code></pre>

<p><code>arr[:None]</code> means <code>0 from the end</code>, and usually is sufficient.</p>

<p>Keep in mind the <code>arr[:i]</code> translates to <code>arr.__getitem__(slice(None,i,None))</code>.  The <code>:</code> syntax is short hand for a <code>slice</code> object.  And the <code>slice</code> signature is:</p>

<pre><code>slice(stop)
slice(start, stop[, step])
</code></pre>

<p><code>slice</code> itself is pretty simple.  It's the <code>__getitem__</code> method that gives it meaning.  You could, in theory, subclass <code>list</code>, and give it a custom <code>__getitem__</code> that treats <code>slice(None,0,None)</code> as <code>slice(None,None,None)</code>.</p>

python arrays numpy