Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle over list indefinitely

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
...
like image 334
Aoki Ahishatsu Avatar asked Mar 28 '19 15:03

Aoki Ahishatsu


People also ask

How do you infinitely loop a list in Python?

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.

How do you cycle through a list in Python?

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.

How do you make a cyclic list?

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.

What are infinite iterators in Python?

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.


2 Answers

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.

like image 166
Filip Młynarski Avatar answered Sep 20 '22 10:09

Filip Młynarski


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
...
like image 24
yatu Avatar answered Sep 19 '22 10:09

yatu