Iterating Through List or Tuple

Fredrik Lundh fredrik at pythonware.com
Tue Jul 22 17:49:00 EDT 2008


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

 >>> import itertools
 >>> help(itertools.cycle)
Help on class cycle in module itertools:

class cycle(__builtin__.object)
  |  cycle(iterable) --> cycle object
  |
  |  Return elements from the iterable until it is exhausted.
  |  Then repeat the sequence indefinitely.

...

 >>> L = [1, 2, 3]
 >>> for i, x in enumerate(itertools.cycle(L)):
...     print i, x
...     if i >= 10:
...             break
...
0 1
1 2
2 3
3 1
4 2
5 3
6 1
7 2
8 3
9 1
10 2
 >>>

</F>




More information about the Python-list mailing list