Python
    About Lesson

    What is Iterators in Python?

    An integrator is an object that can be iterated upon which means that you can traverse through all the values. List, tuples, dictionaries, and sets are all iterable objects.

    To create an object as an iterator you have to implement the methods __iter__() and __next__() to your object where –

    __iter__() returns the iterator object itself. This is used in for and in statements.

    __next__() method returns the next value in the sequence. In order to avoid the iteration going on forever, raise the StopIteration exception.

    Example

    # define a list
    my_list = [4, 7, 0, 3]
    
    # get an iterator using iter()
    my_iter = iter(my_list)
    
    # iterate through it using next()
    
    # Output: 4
    print(next(my_iter))
    
    # Output: 7
    print(next(my_iter))
    
    # next(obj) is same as obj.__next__()

    Why use iterators?

    Iterators allow us to create and work with lazy iterable which means you can use an iterator for the lazy evaluation. This allows you to get the next element in the list without re-calculating all of the previous elements. Iterators can save us a lot of memory and CPU time.

    Python has many built-in classes that are iterators, Example, enumerate, map, filter, zip and reversed, etc. Objects are iterators