Iterating Through List or Tuple

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue Jul 22 17:49:42 EDT 2008


On Tue, 22 Jul 2008 14:43:10 -0700, Samir wrote:

> Is there a way to loop or iterate through a list/tuple in such a way
> that when you reach the end, you start over at the beginning?  For
> example, suppose I define a list "daysOfWeek" such that:
> 
>>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
> 
> If today is Sunday, I can set the variable "day" to today by:
> 
>>>> i = iter(daysOfWeek)
>>>> day = i.next()
>>>> print day
> sunday
> 
> If I want to find out the day of the week 2 days from now, then this
> code works ok:
> 
>>>> for x in xrange(2): day = i.next()
> 
>>>> print day
> tuesday
> 
> However, when extending my range beyond the number of items in the
> list, I receive an error.  For example, if I want to find out the day
> of the week 11 days from today, I get this:
> 
>>>> for x in xrange(11): day = i.next()
> 
> 
> Traceback (most recent call last):
>   File "<pyshell#87>", line 1, in <module>
>     for x in xrange(11): day = i.next()
> StopIteration
> 
> Is there a way to easily loop through a list or tuple (and starting
> over at the beginning when reaching the end) without having to resort
> to an "if" or "while" statement?

For sequences:  days_of_week[(today + offset) % len(days_of_week)]

For iterables in general:  `itertools.cycle()`

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list