Search code examples
pythonloopsenumerate

python continuing a loop from a specific index


I wrote some code that uses enumerate to loop through a list.

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

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.

The part that I am having trouble with is python's enumerate function.

The docs say you can do:

for index, item in enumerate(list, start_index):
    print(str(index))

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.

I wrote a small program and it does indeed act wonky.

>>> 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

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..

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

My expected outcome would be

>>> 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

instead of starting the index at the start position provide.


Solution

  • Actually if you got range object it's not a big deal to make a slice from it, because range(n)[:4] is still range object(as @MosesKoledoye mentioned it's Python 3 feature). But if you got a list, for the sake of not creating new list you can choose itertools.islice, it will return iterator.

    from itertools import islice
    for index, item in enumerate(islice(range(20), 4, None)):
        print(index, item)
    

    Output

    0 4
    1 5
    2 6
    3 7
    4 8
    ...