Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I find it easier to remember how it's works, then I can figure out any specific start/stop/step combination.</p> <p>It's instructive to understand <code>range()</code> first:</p> <pre><code>def range(start=0, stop, step=1): # illegal syntax, but that's the effect i = start while (i &lt; stop if step &gt; 0 else i &gt; stop): yield i i += step </code></pre> <p>Begin from <code>start</code>, increment by <code>step</code>, do not reach <code>stop</code>. Very simple.</p> <p>The thing to remember about negative step is that <code>stop</code> is always the excluded end, whether it's higher or lower. If you want same slice in opposite order, it's much cleaner to do the reversal separately: e.g. <code>'abcde'[1:-2][::-1]</code> slices off one char from left, two from right, then reverses. (See also <a href="http://www.python.org/dev/peps/pep-0322/" rel="noreferrer"><code>reversed()</code></a>.)</p> <p>Sequence slicing is same, except it first normalizes negative indexes, and can never go outside the sequence:</p> <p><strong>TODO</strong>: The code below had a bug with "never go outside the sequence" when abs(step)>1; I <em>think</em> I patched it to be correct, but it's hard to understand.</p> <pre><code>def this_is_how_slicing_works(seq, start=None, stop=None, step=1): if start is None: start = (0 if step &gt; 0 else len(seq)-1) elif start &lt; 0: start += len(seq) if not 0 &lt;= start &lt; len(seq): # clip if still outside bounds start = (0 if step &gt; 0 else len(seq)-1) if stop is None: stop = (len(seq) if step &gt; 0 else -1) # really -1, not last element elif stop &lt; 0: stop += len(seq) for i in range(start, stop, step): if 0 &lt;= i &lt; len(seq): yield seq[i] </code></pre> <p>Don't worry about the <code>is None</code> details - just remember that omitting <code>start</code> and/or <code>stop</code> always does the right thing to give you the whole sequence.</p> <p>Normalizing negative indexes first allows start and/or stop to be counted from the end independently: <code>'abcde'[1:-2] == 'abcde'[1:3] == 'bc'</code> despite <code>range(1,-2) == []</code>. The normalization is sometimes thought of as "modulo the length" but note it adds the length just once: e.g. <code>'abcde'[-53:42]</code> is just the whole string.</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