How can I iterate over a list from a specific index?

I found the answer here, but it didn’t work for me Index access in Python loops for loops

I am trying to execute a 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 conclusion is

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 at index 1 and go to the end.

+4
source share
5 answers

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

for item in ints[1:]:

This will cause your list to skip the 0th item. Since you really don't need an index, this implementation is clearer than those that unnecessarily support the index

+5

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

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

, , . , , , :

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

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

:

1 3
2 4
3 5
4 hi

Alternatively, if you want to iterate over all elements, but print indexes starting with 1 instead of 0:

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

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

exit:

1 1
2 3
3 4
4 5
5 hi

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

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

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

exit:

1 1
2 3
3 4
4 5
5 hi
+1
source

Solution for iterations too (not just lists):

def enumerate_from(start_index, iterable):
    for i, x in enumerate(iterable):
        if i >= start_index:
            yield i, x
0
source

You can 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)
0
source

Source: https://habr.com/ru/post/1621011/


All Articles