Iterators

In Python, an iterator is an object that can be iterated upon. It is an object that will return data, one element at a time. Python's iterator object implements two methods, __iter__() and __next__(). Mostly, iterators are implemented within loops, generators, and comprehensions.

In the following example, we are using the next() function, which will iterate through all of the items. After reaching the end and there is no more data to be returned, it will raise StopIteration, as shown in the following example:

numbers = [10, 20, 30, 40]

numbers_iter = iter(numbers)

print(next(numbers_iter))
print(next(numbers_iter))
print(numbers_iter.__next__())
print(numbers_iter.__next__())

next(numbers_iter)

Output:
10
20
30
40
Traceback (most recent call last):
File "sample.py", line 10, in <module>
next(numbers_iter)
StopIteration

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset