Infinite iterators in Python

Python Methods and Functions

Python provides three types of infinite iterators —

  1. count (start, step): this iterator starts printing at the number "start" and prints endlessly . If steps are mentioned, numbers are skipped, otherwise step is 1 by default. See the example below for using it with a for in loop.

    Example :

    # Program Python for demonstration
    # infinite iterators

     

    import itertools

     
    # for in a loop

    for i in itertools.count ( 5 , 5 ):

      if i = = 35 :

      break

    else :

    print (i, end = "" )

    Exit:

     5 10 15 20 25 30 
  2. loop (iterable): this iterator prints all values ​​in order from the given container. It resumes printing from the beginning again when all items are printed cyclically.

    Example # 1:

    # Python program for demonstration
    # infinite iterators

      

    import itertools

     

    count = 0

     
    # for in a loop

    for i in itertools.cycle ( 'AB' ):

      if count & gt;  7 :

    break

    else :

    print (i, end = "" )

    count + = 1

    Exit :

     ABABABAB 

    Example # 2: Using the following function.

    # Python program for demonstration
    # endlessly nite iterators

     

    import itertools

     

    l = [ 'Geeks' , 'for' , ' Geeks' ]

     
    # iterator definition

    iterators = itertools.cycle (l)

     
    # for in a loop

    for i in range ( 6 ):

     

    # Using the following function

    print ( next (iterators), end = " " )

    Exit:

     Geeks for Geeks Geeks for Geeks 
  3. repeat (val, num): this iterator repeatedly prints the passed value an infinite number of times. If the optional keyword num is mentioned, it prints num multiple times.

    Example :

    # Python code to demonstrate how it works
    # repeat ()

     
    # import & quot; itertools & quot; for iterator operations

    import itertools 

     
    # using repeat () to repeatedly print the number

    print ( "Printing the numbers repeatedly:"

    print ( list (itertools.repeat ( 25 , 4 )))

    Exit :

     Printing the numbers repeatedly: [25, 25, 25, 25] 




Get Solution for free from DataCamp guru