Skip to main content

Iterator object in Python

Python iterable object

The 'list' object is one of iterable objects. This makes it possible to consume its elements using a for loop.
fruits = ['apple', 'orange', 'grape', 'peach']
print(type(fruits))
for elm in fruits:
  print(elm)

# class 'list'
# apple
# orange
# grape
# peach

Explicitly create a Python iterator using iter, which is a Built-in Function in Python.

iter(object[, sentinel])

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

Use iter function to create an iterable object and call the elements in the iterator with `next` function.
it = iter(fruits)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))

# apple
# orange
# grape
# peach
# ---------------------------------------------------------------------------
# StopIteration                             Traceback (most recent call last)
# ...
If the iterator is exhausted, StopIteration is raised.
next(iterator[, default])

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

Comments