+ 5
Can someone explain cycle module?
I don't understand how cycle module works, so can someone please explain it thoroughly.
1 Answer
+ 1
from itertools import cycle
# using itertools cycle, an example.
# this allows the cyclic production of values 1-5
thecycle = cycle([1,2,3,4,5])
# you can do the same thing yourself
# without itertools if you want to.
def mycycle():
num = 0
while 1:
yield (num % 5)+1
num +=1
doityourself = mycycle()
for i in range(20):
# value output comparison
print(next(thecycle),next(doityourself))
# the advantage of itertools is mutiple features
# are built in and ready to go. Read about
# generators as a starting point to learn more