a = 1
b = 2
c = 3
x = a
def change_x():
x = next??
print("x:", x)
for i in range(10):
change_x()
How can I cycle through a, b, c by calling change_x() indefinitely?
Output should be:
x: 2
x: 3
x: 1
x: 2
...
You can use module to keep it simple. Just make sure not to start iterating from 0. You can start the range at 0 , easily, by simply using for i in range(0, 100): print(my_list[i % len(my_list)]) but in any case this will only iterate 100 times, the op wants to keep cycling indeterminately.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
Method #1 : Using % operator + loop The % operator can be used to cycle the out of bound index value to begin from the beginning of list to form a cycle and hence help in the cyclic iteration.
Iterator in Python is any python type that can be used with a ' for in loop '. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite.
You could use cycle()
and call next()
as many times as you want to get cycled values.
from itertools import cycle
values = [1, 2, 3]
c = cycle(values)
for _ in range(10):
print(next(c))
Output:
1
2
3
1
2
3
1
2
3
1
or as @chepner suggested without using next()
:
from itertools import islice
for i in islice(c, 10):
print(i)
To get the same result.
You can use itertools.cycle
, to cycle around the values in a
, b
and c
as specified:
from itertools import cycle
for i in cycle([a,b,c]):
print(f'x: {i}')
Output
x: 1
x: 2
x: 0
x: 1
x: 2
x: 0
x: 1
x: 2
x: 0
x: 1
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With