Explain the use of iterators and their importance
An iterator
is an object that can be "traversed" through. In other words, it is an object that can be accessed in iterations
in place of the full object.
In Python, an iterator
is any object that implements the iterator protocol. The protocol contains two built-in functions (iter()
and next()
). A list
is a built-in iterator in python. However, to invoke next()
, we would still need to convert it to an iterator object using the iter()
method.
PYTHON
1newList = [1, 2, 3, 4, 5]
2next(newList)
The output will be the following error:
This is because it is not fully implementing the iterator protocol.
PYTHON
1newList = [1, 2, 3, 4, 5]
2object = iter(newList)
3next(object)
Now that it's fully implementing the protocol, our output will be:
PYTHON
11
xxxxxxxxxx
# newList = [1, 2, 3, 4, 5]
# next(newList)
newList = [1, 2, 3, 4, 5]
object = iter(newList)
next(object)
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment