Infinite Iterator in python
Without using while loop we can do all the operation in for loop also by using infinite Iterators. If we give break statement then only the process will stop,Otherwise it will continously print the values.
count
"count" in itertool will repeat the "for" loop iteration for infinite number of times. To end the "for" loop we have to give the condition.
Syntax:
count(start,step) or count(start)
from itertools import count for i in count(5): print(i, end = " ")
Output
5 6 7 8 9 10 11 12 13 14 etc...
from itertools import count for i in count(5,3): print(i,end=" ")
Output
5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 etc...
Cycle
"cycle" in itertool will repeat the given elements for n number of times.
Syntax:
cycle(iterable)
from itertools import cycle n = [ 1, 2, 3] for i in cycle(n): print(i,end=" ")
Output
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 ..etc
Repeat
repeat(value) -> If the condition is not given, it will repeat the loop for infinite number of times.
repeat(value,no.of.times) -> "repeat" in itertool will repeat the given element for the given number of times.
Syntax:
repeat(value) or repeat(value,no.of.times)
from itertools import repeat for i in repeat(1): print(i,end = " ")
Output
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 etc...
from itertools import repeat for i in repeat(5,4): print(i,end = " ")
Output
5 5 5 5
Islice
If the condition is not given, it will repeat the loop for infinite number of times.
Syntax:
islice(count(start) , no.of.times to stop))
from itertools import count,islice for i in islice(count(3),5): print(i,end = " ")
Output
3 4 5 6 7
from itertools import count,islice for i in islice(count(5),3): print(i,end = " ")
Output
5 6 7
Next
To use "next" function first of all we have to create "iter" function element. "next" function is to get the next element to the current element.
Syntax:
next(iterators)
n = [1,3,5,7] a = iter(n) print(next(a)) print(next(a)) print(next(a)) print(next(a))
Output
1 3 5 7