Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can loop through a list from a certain index?

Tags:

python

loops

list

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.

like image 418
Eric MacLeod Avatar asked Dec 20 '15 18:12

Eric MacLeod


1 Answers

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

like image 179
pvg Avatar answered Sep 19 '22 16:09

pvg