Thursday, June 27, 2013

Continuously loop (cycle) through a list in python

Thank you itertools:
In [7]: a=[1,2,3]

In [8]: licycle = itertools.cycle(a)

In [9]: licycle.next()
Out[9]: 1

In [10]: licycle.next()
Out[10]: 2

In [11]: licycle.next()
Out[11]: 3

In [12]: licycle.next()
Out[12]: 1

In [13]: licycle.next()
Out[13]: 2

In [14]: licycle.next()
Out[14]: 3

In [15]: licycle.next()
Out[15]: 1

In [16]: licycle.next()
Out[16]: 2

In [17]: licycle.next()
Out[17]: 3

No comments: