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?
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."
You can use slicing:
for item in some_list[2:]: # do stuff
This will start at the third element and iterate to the end.
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): ...
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