How do you start a loop from a specified index in python?

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?

asked May 27, 2011 at 6:28

Vincent CatalanoVincent Catalano

2,1794 gold badges21 silver badges29 bronze badges

3

You can use slicing:

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

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

answered May 27, 2011 at 6:31

Björn PollexBjörn Pollex

73.4k28 gold badges192 silver badges276 bronze badges

8

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):
    ...

answered May 27, 2011 at 6:49

How do you start a loop from a specified index in python?

John La RooyJohn La Rooy

285k50 gold badges358 silver badges498 bronze badges

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.

answered May 27, 2011 at 6:35

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])

answered Jul 14, 2020 at 20:05

How do you start a loop from a specified index in python?

Charlie SuCharlie Su

3283 silver badges7 bronze badges

1

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

73.4k28 gold badges192 silver badges276 bronze badges

answered May 27, 2011 at 9:16

How do you start a loop from a specified index in python?

synthesizerpatelsynthesizerpatel

26.6k5 gold badges72 silver badges90 bronze badges

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

answered May 27, 2011 at 7:17

juanchopanzajuanchopanza

219k31 gold badges390 silver badges464 bronze badges

1

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']
>>>

answered May 27, 2011 at 8:52

John MachinJohn Machin

79.4k11 gold badges138 silver badges183 bronze badges

2

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 )

answered May 27, 2011 at 8:19

slothropslothrop

1,0176 silver badges7 bronze badges

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

answered Feb 2 at 19:52

How do you start a loop at a specific index in Python?

Use slicing to start a for loop at index 1 Use slice notation [start:] with start as 1 to create a copy of the sequence without the element at index 0 . Iterate over the sliced sequence. To start the loop at an element at a different index, set start to the desired index.

How do you use the loop index in Python?

To check the index in for loop you can use enumerate() function. In Python, the enumerate() is an in-built function that allows us to loop over a list and count the number of elements during an iteration with for loop. There are various method to check how to check the index in for loop in Python.

How do I loop a second index in Python?

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.

How do you start writing a loop in Python?

Let's go over the syntax of the for loop: It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with “ : ”.