In this topic, we will learn about the concept of iterator in Python.
The iterator is an object that contains a finite number of values.
Lists, tuples, sets, strings and dictionaries are the examples of iterable objects. These are basically iterable containers which we can get an iterator from.
An iterator helps in traversing through (i.e. iterating upon) all the values of iterable objects and consists of the methods next() and iter().
The next() method retrieves the next item from an iterable object. When we reach the end and there is no more data to be returned, it will raise
We can also use a for loop to iterate through an iterable object.
A list is an iterable and we can get iterator from it by using iter() function in Python. See the code below:
# Iterable object1: a sample list
mylist = ["pen", "pencil", "eraser", "ruler", "chalk"]
mylist = iter(mylist) # using iter() method to get an iterator
# using next() method to get the next item from an iterable
print(next(mylist)) # raises StopIteration error
print("StopIteration Error occurred!")
# Iterable object2: a sample string
mystr = "mother"
# using simple for loop
for item in mystr:
StopIteration Error occurred!