Iterators in Python?

Question

What are iterators in Python?

in progress 0
Pragya Rani 4 years 1 Answer 666 views Contributor 0

Answer ( 1 )

  1. Iterators are everywhere in Python. They are elegantly implemented within for loops, comprehensions, generators etc. but are hidden in plain sight.

    An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc. are iterables.

    Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

    We use the next() function to manually iterate through all the items of an iterator. When we reach the end and there is no more data to be returned, it will raise the StopIteration Exception. Following is an example.

    # define a list
    my_list = [4, 5, 0, 4]

    # get an iterator using iter()
    my_iter = iter(my_list)

    # iterate through it using next()

    # Output: 4
    print(next(my_iter))

    # Output: 5
    print(next(my_iter))

    # next(obj) is same as obj.__next__()

    # Output: 0
    print(my_iter.__next__())

    # Output: 4
    print(my_iter.__next__())

    # This will raise error, no items left
    next(my_iter)
    Run Code
    Output

    4
    5
    0
    4
    Traceback (most recent call last):
    File “”, line 24, in
    next(my_iter)
    StopIteration

    A more elegant way of automatically iterating is by using the for loop. Using this, we can iterate over any object that can return an iterator, for example list, string, file etc.

    >>> for element in my_list:
    … print(element)

    4
    5
    0
    4

Leave an answer

Browse
Browse