113

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?

Vincent Catalano
  • 2,259
  • 4
  • 22
  • 29

9 Answers9

227

You can use slicing:

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

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

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
58

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):
    ...
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
22

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])
Charlie Su
  • 427
  • 4
  • 8
13

You can always loop using an index counter the conventional C style looping:

for i in range(len(l)-1):
    print l[i+1]

It is always better to follow the "loop on every element" style because that's the normal thing to do, but if it gets in your way, just remember the conventional style is also supported, always.

lprsd
  • 84,407
  • 47
  • 135
  • 168
11

stdlib will hook you up son!

deque.rotate():

#!/usr/local/bin/python2.7

from collections import deque

a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
a.rotate(3)
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
synthesizerpatel
  • 27,321
  • 5
  • 74
  • 91
5

If all you want is to print from Monday onwards, you can use list's index method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Using list.index saves you hard-coding the index for "Monday", which is a potential source of error:

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for d in days[days.index('Monday'):] :
   print d
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
5

Here's a rotation generator which doesn't need to make a warped copy of the input sequence ... may be useful if the input sequence is much larger than 7 items.

>>> def rotated_sequence(seq, start_index):
...     n = len(seq)
...     for i in xrange(n):
...         yield seq[(i + start_index) % n]
...
>>> s = 'su m tu w th f sa'.split()
>>> list(rotated_sequence(s, s.index('m')))
['m', 'tu', 'w', 'th', 'f', 'sa', 'su']
>>>
John Machin
  • 81,303
  • 11
  • 141
  • 189
0

If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):

dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
            'Friday', 'Saturday',  ]

startDayName = 'Monday'

startIndex = dayNames.index( startDayName )
print ( startIndex )

rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]

for x in rotatedDayNames:
    print ( x )
slothrop
  • 3,218
  • 1
  • 18
  • 11
0

Loop whole list (not just part) starting from a random pos efficiently:

import random
arr = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
cln = len(arr)
start = random.randint(0, cln-1)
i = 0
while i < cln:
    pos = i+start
    print(arr[pos if pos<cln else pos-cln])
    i += 1
Andrei .F
  • 31
  • 4