python continuing a loop from a specific index
<p>I wrote some code that uses enumerate to loop through a list.</p>

<pre><code>for index, item in enumerate(list[start_idx:end_idx])
     print('index [%d] item [%s]'%(str(index), item))
</code></pre>

<p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll slice up the list do do different things.</p>

<p>The part that I am having trouble with is python's enumerate function.</p>

<p>The docs say you can do:</p>

<pre><code>for index, item in enumerate(list, start_index):
    print(str(index))
</code></pre>

<p>the above code doesn't do what I expected. I though enumerate would start at the start position and stop at the end, but it doesn't.</p>

<p>I wrote a small program and it does indeed act wonky.</p>

<pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4):
...      print(str(i)+'\t'+str(x))
... 
4   0
5   1
6   2
7   3
8   4
9   5
10  6
11  7
12  8
13  9
14  10
15  11
16  12
17  13
18  14
19  15
20  16
21  17
22  18
23  19
</code></pre>

<p>I would expect enumerate to start at index 4 and loop to the end. So it would get the range of 4-19 but it seems to just start the index but still iterates from 0-19..</p>

<p>Question, is there a way to do a iteration loop starting at a specific index in python?</p>

<p>My expected outcome would be</p>

<pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4):
...      print(str(i)+'\t'+str(x))
... 
4   0 # skip
5   1 # until
6   2 # this
7   3 # item
8   4
9   5
10  6
11  7
12  8
13  9
14  10
15  11
16  12
17  13
18  14
19  15
20  16
21  17
22  18
23  19
</code></pre>

<p>instead of starting the index at the start position provide.</p>

<p>The <code>start</code> parameter of <code>enumerate</code> doesn't have anything to do with what elements of the iterable get selected. It just tells enumerate what number to start with.</p>

<pre><code>&gt;&gt;&gt; list(enumerate(range(3)))
[(0, 0), (1, 1), (2, 2)]
&gt;&gt;&gt; list(enumerate(range(3), 1))
[(1, 0), (2, 1), (3, 2)]
</code></pre>

<p>If you want to start at a specific index, you need to provide the start argument <em>and</em> a <a href="https://docs.python.org/dev/library/functions.html#slice" rel="nofollow">slice</a>:</p>

<pre><code>for i, v in enumerate(alist[4:], 4):
    ...
</code></pre>

python loops enumerate