Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start index for iterating Python list

What is the best way to set a start index when iterating a list in Python. For example, I have a list of the days of the week - Sunday, Monday, Tuesday, ... Saturday - but I want to iterate through the list starting at Monday. What is the best practice for doing this?

like image 732
Vincent Catalano Avatar asked May 27 '11 06:05

Vincent Catalano


People also ask

Does a for loop start at 0 or 1?

The reason a lot of for loops start at 0 is because they're looping over arrays, and in most languages (including JavaScript) arrays start at index 0."


2 Answers

You can use slicing:

for item in some_list[2:]:     # do stuff 

This will start at the third element and iterate to the end.

like image 146
Björn Pollex Avatar answered Sep 19 '22 22:09

Björn Pollex


islice has the advantage that it doesn't need to copy part of the list

from itertools import islice for day in islice(days, 1, None):     ... 
like image 37
John La Rooy Avatar answered Sep 17 '22 22:09

John La Rooy