9

I found the answer here but it doesn't work for me Accessing the index in Python 'for' loops

I'm trying to loop from the second index

ints = [1, 3, 4, 5, 'hi']

for indx, val in enumerate(ints, start=1):
    print indx, val

for i in range(len(ints)):
   print i, ints[1]

My output is this

1 1
2 3
3 4
4 5
5 hi
0 3
1 3
2 3
3 3
4 3

I need to get the first integer printed out at index 1 and loop through to the end.

Community
  • 1
  • 1
Eric MacLeod
  • 451
  • 3
  • 7
  • 18

5 Answers5

15

A simple way is to use python's slice notation - see the section in the basic tutorial. https://docs.python.org/2/tutorial/introduction.html

for item in ints[1:]:

This will iterate your list skipping the 0th element. Since you don't actually need the index, this implementation is clearer than ones that maintain the index needlessly

pvg
  • 2,673
  • 4
  • 17
  • 31
10

Try

for idx, val in enumerate(ints[1:], start=1)
    print idx, val

Or

for i in range(1, len(ints)):
    print i, ints[i]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
3

I'm not sure I fully understand what you're trying to achieve. To my understanding, if you just want to loop through the list starting at the second element you can do this:

ints = [1, 3, 4, 5, 'hi']

for i in range(1,len(ints)):
    print i, ints[i]

output:

1 3
2 4
3 5
4 hi

Alternatively, if you want to loop through all elements, but print the indices starting from 1 instead of 0:

ints = [1, 3, 4, 5, 'hi']

for i in range(len(ints)):
    print i+1, ints[i]

output:

1 1
2 3
3 4
4 5
5 hi

Or using enumerate() going through all elements, but print the indices starting at 1 instead of 0:

ints = [1, 3, 4, 5, 'hi']

for i, el in enumerate(ints):
    print (i+1), el

output:

1 1
2 3
3 4
4 5
5 hi
Simon
  • 9,762
  • 15
  • 62
  • 119
2

You could use itertools.islice:

import itertools

for idx, el in enumerate(itertools.islice(ints, 1, None), start=1):
    print(idx, el)

Or if you just want to skip the first element:

for idx, el in enumerate(ints):
    if idx == 0:
        continue
    print(idx, el)
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

A solution for iterables too (not only lists):

def enumerate_from(start_index, iterable):
    for i, x in enumerate(iterable):
        if i >= start_index:
            yield i, x
Caridorc
  • 6,222
  • 2
  • 31
  • 46