What are iterators in Python?
An iterator is an object that gives you the items of a collection one at a time. It follows the iterator protocol, which means it has two methods: __iter__() and __next__(). A list, tuple or string is an iterable, and you get an iterator from it with iter().
nums = [10, 20, 30]
it = iter(nums)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
Output:
Tutorials Class - Output Window
10
20
30
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(next(it))
StopIteration
When there are no items left, the iterator raises StopIteration. A for loop calls iter() and next() for you and stops quietly when this happens. Compare it with a generator, which is an easy way to create an iterator.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |