Given a list of n elements where n>1, I want to be able to iterate over the list and be able to repeat infinitely. If I reach the end of the list, I want to restart it. The catch here is that speed is what matters the most, so I don't want to create a method or use try catch statements. I currently do keep a current_player like this:
class Player():
pass #whatever the player is
#Initialisaiton
players = [Player(), Player(), Player()]
current_player_index = 0
current_player = players[current_p´layer_index]
#Game loop:
turn_count = 0
while(turn_count < 100): #any number of max turns
turn_count += 1
current_player_index += 1
if current_player_index == len(players):
current_player_index = 0
current_player = players[current_player_index]
I'm just asking about a fast way to iterate an iterable in an infinite cycle.
Another example: The iterable can be food=["h","a","m"]. I want to know if there is a way to call next(food), lets say 10 times, and get "hamhamhamh" if all the outputs were concatenated
Thank you! The accepted answer looks like this:
import itertools
class Player():
pass #whatever the player is
#Initialisaiton
players = [Player(), Player(), Player()]
players_iterable = itertool.cycle(players)
current_player = next(players_iterable)
#Game loop:
turn_count = 0
while(turn_count < 100): #any number of max turns
turn_count += 1
current_player = next(players_iterable)