+ 2

[Solved]How do I update the limit of an iteration during the loop?

Hello people! How are you? I have the following problem. I have a list of objects that is constantly updated, losing and gaining new individuals. I need to do a check on all of them to see which ones will come out. However, I realized that the "for" command does not keep the iteration list up to date. It checks the size once and executes the commands N times. At least that's what I understood trying to do something like this: https://code.sololearn.com/clyZJmEmnhGQ/#py Sorry, I'm using the SoloLearn web version and I couldn't include the code directly How can I update the maximum number of iterations? [Solution in the comments]

8th Mar 2020, 2:04 PM
rfPeixoto
rfPeixoto - avatar
5 odpowiedzi
+ 6
[edited]: I found this post that may help you: https://stackoverflow.com/questions/21047108/how-to-restart-for-loop-in-JUMP_LINK__&&__python__&&__JUMP_LINK/21047219 The code does delete elements inside a for loop. The condition for the for loop is a range that is calculated by the number of elements. So you will run in an index error. What you need is to "restart" the loop from inside. What you can do is to replace the for loop by a while loop, so you can control everything yourself. An other possible way is to put a while loop "around" the for loop. In this case you can navigate the program flow with break / continue.
8th Mar 2020, 2:31 PM
Lothar
Lothar - avatar
+ 3
When you are looping over a range, you are not looping over that list of yours. The range is a separate iterable, dishing out numbers. You can also loop over the actual list: for element in your_list: print(element) If you do this, you can change the list while you're looping over it. This is generally not recommended though, it can make it hard to control what's going on and cause errors. Do you maybe want to tell us a specific case where you would want to do this? There's probably a safer solution.
8th Mar 2020, 2:17 PM
HonFu
HonFu - avatar
+ 2
Thank you both for the responses! Yes, I used the range () to ensure that what will be used there would be an int. I updated the sample code to exactly what I am trying to do. It's a simple simulation: I have a scenario with N creatures. I want to see how they multiply given an N number of available resources. There are probably better ways to make the entire code, but it is just for learning. I'll test what I can with 'while' and edit here if I find the solution.
8th Mar 2020, 2:48 PM
rfPeixoto
rfPeixoto - avatar
+ 2
Solved! I Include a counter inside the method, but outside the 'for' and I used this counter as the list ID. I don't know if it's the best way, but it worked. Thank you! (I updated the code in case someone needs to see how to solve something similar)
8th Mar 2020, 3:26 PM
rfPeixoto
rfPeixoto - avatar
+ 2
rfPeixoto, looks great now. Nice code. 👍
8th Mar 2020, 6:43 PM
Lothar
Lothar - avatar