itertools - cycle()
An infinite list that follows a cyclical pattern
Cycle is one of those functions you may need, but instead created your own workaround on it.
If you check the documentation, you will read the function will create an iterator that returns elements from the passed iterable, saving a copy of each. What does it mean, in practical terms?
To explain this in a better way, I will create an example better than the one shown in the docs1.
Imagine a simple monopoly game, where you have multiple player objects, and each one holds multiple information like the amount of money the player currently have, and the list of properties in the portfolio. what is the best way to keep the gaming going on, with each player playing on its turn? You could create a counter outside of the loop, and access the player using the counter. When the counter gets bigger than the number of players, we reset the counter to make it go back to the first position. Somethings like this:
This C-style code is not that bad, but we are doing a lot of work to control one variable. Cycle allow you to do this in a more pythonic way.
After creating the array of players (same way as before), you can do a for loop in cycle(players) that will make a copy of whatever is the state right after you use the elements, meaning the changes are carried over to the next time it appears in the loop. Something like this:
The number of variable you have to control are small, and there is no need to keep track of any extra variable.
Now, if you do want to store additional information, remember cycle returns a generator and can be combined with other elements in python, like enumerate(), which would keep a counter of the items already looped. This don't mean you should never use an external counter, but it is good to know you have more options, that may be easier to implement, while keeping the code organised.
When to NOT use it
In most cases, it should be ok to perform actions using cycle, but remember a copy of the element is added at the end of the list, which may require more storage2
Using the examples above, if you game has a humongous amount of loops, then it may be better to move back to that external index variable
their example was resumed into a comment: # cycle('ABCD') → A B C D A B C D A B C D ...
Could be memory, could be disk.



