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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With