Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python enumerate list setting start index but without increasing end count

Tags:

python

I want to loop through a list with a counter starting at zero but with the list starting index at 1 eg:

valueList = [1, 2, 3, 4]
secondList = ['a', 'b', 'c', 'd']

for i, item in enumerate(valueList, start=1):
    print(secondList[i])

The code fails with an index out of range error (I realize this is because i ends at the length of the list -1 plus the start value and that python lists are zero indexed so using i in this way to call the ith element in another list is not valid). The following works but the addition of the test for i greater than zero looks un-pythonic.

valueList = [1, 2, 3, 4]
secondList = ['a', 'b', 'c', 'd']

for i, item in enumerate(valueList, start=0):
    if i > 0:  
        print(secondList[i]) 

Enumerate is not the right choice, is there another way?

like image 341
Don Smythe Avatar asked Mar 21 '15 09:03

Don Smythe


1 Answers

It sounds as if you want to slice the list instead; still start enumerate() at one to get the same indices:

for i, item in enumerate(valueList[1:], start=1):

This then loops over valueList starting at the second element, with matching indices:

>>> valueList = [1, 2, 3, 4]
>>> secondList = ['a', 'b', 'c', 'd']
>>> for i, item in enumerate(valueList[1:], start=1):
...     print(secondList[i])
... 
b
c
d

In this case, I'd just use zip() instead, perhaps combined with itertools.islice():

from itertools import islice

for value, second in islice(zip(valueList, secondList), 1, None):
    print(value, second)

The islice() call skips the first element for you:

>>> from itertools import islice
>>> for value, second in islice(zip(valueList, secondList), 1, None):
...     print(value, second)
... 
2 b
3 c
4 d
like image 122
Martijn Pieters Avatar answered Oct 21 '22 08:10

Martijn Pieters