+ 1

PYTHON - "SHORTEN" A FOR LOOP RUNNING WITH CYCLE()?

Hey, I got a little learning program, and was wondering how or better IF I can change the conditional of the for loop while it's running? I got a list with class-objects in it. I made a range with the length of the list and the itertools-function CYCLE. for i in cycle(range(len(LIST))): My question now is: Am I right in the assumption that that cycle is carved into stone after I started the loop? Because I can delete as many List-items as I want, but it still iterates as if there were still as many items in the list as there were in the beginning, and then consequently produces an error since there are less objects in there. ^^

29th Jan 2019, 6:28 PM
Scalrion
Scalrion - avatar
4 odpowiedzi
+ 5
Yeah, with cycle you create a generator that will stick to the range you initially gave it. I think you can easily simulate the behavior you want if you put a while loop around your for loop so that when the for ends it will just start over. Changing a list while iterating over it can be tricky... better even if you wouldn't have to do it, but that's another matter.
29th Jan 2019, 7:24 PM
HonFu
HonFu - avatar
+ 3
In this case the while loop seems to be a better fit. The cycle repeats the same number of times always, but you have fewer and fewer elements in the list. So in the while loop you have more flexibility to adjust the iteration variable, and define the exit condition (when there is only one left).
29th Jan 2019, 9:47 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Okidoke. Thanks for the input. I will change that accordingly. :)
29th Jan 2019, 10:03 PM
Scalrion
Scalrion - avatar
+ 1
Well my Program is an Assignment on here. X people stand in a circle. The first stabs/kills the second the third kills the fourth and so an. In the end you should know who survived. I added HP and STR with randin(1,3) Values and the Option of not hitting the next person. So it has to be circular. I tried it with while at first I just thought that it would be easier with the cycle function. ^^
29th Jan 2019, 7:37 PM
Scalrion
Scalrion - avatar