+ 1
What are ways to limit a for loop applied to a circular/cyclic list in Python
I'm trying to get to know multiple ways to make for loop finite that iterates over a cyclic/circular list.
8 Answers
+ 14
Hmm... I could imagine a for loop with enumerate(list_name) increasing the counter with each list item. When the counter reaches the full cycle -- len(list_name) -- you break. If you want two cycles - you break at 2 * len(list_name) and so on.
I'm just not sure how would enumerate behave with a cyclical list đ€
+ 4
You can use break to exit a for loop at an arbitrary point.
Check the standard doc for examples:
https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
+ 4
OK one more trivial option is that your for loop is inside a function, and you terminate the cycle by returning the function value. Example with an actual infinite iterator:
https://code.sololearn.com/cylm2EaIAYAz/?ref=app
+ 4
Or use a generator to control the (infinite) loop from outside the function:
def generate_numbers():
numbers = list(range(1, 11))
index = 0
while True:
yield numbers[index%len(numbers)]
index += 1
numbers = generate_numbers()
l = []
while len(l) < 25:
l.append(next(numbers))
+ 3
Ok another idea is to raise an error to break the loop. Check this:
https://code.sololearn.com/c5nJcn242mPj/?ref=app
+ 2
https://code.sololearn.com/cOqWWHwl9hsE/?ref=app
0
Yes, that is a way to exit a for loop
0
Kuba SiekierzyĆski can you suggest other ways to do it?