What are ways to limit a for loop applied to a circular/cyclic list in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

25th Mar 2019, 7:00 AM
Hardik Khane
Hardik Khane - avatar
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 🤔
27th Mar 2019, 6:38 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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
26th Mar 2019, 8:40 PM
Tibor Santa
Tibor Santa - avatar
+ 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
27th Mar 2019, 10:21 AM
Tibor Santa
Tibor Santa - avatar
+ 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))
27th Mar 2019, 10:36 AM
Anna
Anna - avatar
+ 3
Ok another idea is to raise an error to break the loop. Check this: https://code.sololearn.com/c5nJcn242mPj/?ref=app
27th Mar 2019, 5:42 AM
Tibor Santa
Tibor Santa - avatar
+ 2
https://code.sololearn.com/cOqWWHwl9hsE/?ref=app
27th Mar 2019, 7:14 AM
Anna
Anna - avatar
0
Yes, that is a way to exit a for loop
27th Mar 2019, 4:09 AM
Hardik Khane
Hardik Khane - avatar
0
Kuba Siekierzyński can you suggest other ways to do it?
27th Mar 2019, 4:11 AM
Hardik Khane
Hardik Khane - avatar