Python itertools; Cyclling through a list

 

If you want to loop through a list in Python, and everytime you hit the last one you loop back and start from the beginning without throwing an exception you can use the Cycle module:


>>> <strong>from itertools import cycle</strong>
>>> my_list = [1,2,3]
>>> <strong>my_cycle = cycle(my_list)</strong>
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s