Python Iterators
Iterators help us in iterating over an iterable object. They are an essential component of every program, no matter how little. They add flexibility to our program and make it more dynamic.
In this article, we will go over all of the key aspects of iterators and gain a thorough grasp of iterators in Python.
What are Iterators in Python?
Iterators are Python objects that iterate over iterable objects. They follow and implement the iterator protocol. The most important method of an iterator is __next__().
How to create Python Iterators?
We can create iterators by using a function called iter(). It takes one iterable argument and returns an iterator-type object. This object is called the iterator.
Syntax
iter(iterable)
Example of creating iterators in Python
iterable = [1, 2, 3, 4] iter_obj = iter(iterable) print(iter_obj) print(type(iter_obj))
Output
<class ‘list_iterator’>
It raises a TypeError when we pass an object which is not iterable.
Example of creating iterators in Python
iterable = 34 iter_obj = iter(iterable) print(iter_obj) print(type(iter_obj))
Output
Implicit Creation of Iterators in Python
We don’t always explicitly create iterators. Many times, Python implicitly creates iterators of an iterable to iterate through the object.
Example of implicit creation of iterators in Python
iterable = [1, 2, 3, 4] def display(num): return num*2 print(list(map(display, iterable)))
Output
In the above code example, when we used the map function, Python automatically converts the passed iterable into an iterator to iterate through the object.
For-Loop and Iterators in Python
For iterating over an iterable object in Python, the for-loop is extremely useful. The for-loop implicitly creates an iterator of the iterable and uses the iterator to iterate through the entire iterable.
Example of using for-loop in Python
iterable = [1, 2, 3, 4] for num in iterable: print(num)
Output
2
3
4
Working of Python Iterators
Although iterators are so powerful and useful, the working of iterators is pretty simple. Iterators iterate through an object with the help of an important function called next(). The function takes an iterator as an argument and returns the subsequent value of that passed iterable.
Syntax
next(iterator)
Example of using next() in Python
iterable = "PythonGeeks" iter_obj = iter(iterable) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj))
Output
y
t
h
o
n
The function next() raises a StopIteration error when there is no subsequent value left to return from the passed object.
Python uses this function in an infinite while-loop to iterate over an object. The loop ends when it encounters the StopIteration error.
Example of working of iterators in Python
iterable = "PythonGeeks" iter_obj = iter(iterable) while True: try: print(next(iter_obj)) except StopIteration: break
Output
y
t
h
o
n
G
e
e
k
s
__next__() in Python
Whenever we call the next() function, Python internally invokes the __next__() magic method. We can use this method directly to iterate over an iterator.
Example of using __next__ in Python
iterable = "PythonGeeks" iter_obj = iter(iterable) print(iter_obj.__next__()) print(iter_obj.__next__()) print(iter_obj.__next__()) print(iter_obj.__next__()) print(iter_obj.__next__()) print(iter_obj.__next__())
Output
y
t
h
o
n
Creating Custom Iterators in Python
Python allows us to create our own custom iterators. Let us create an iterator
Example of creating custom iterators in Python
class Integers: def __init__(self, max_limit): self.max_limit = max_limit def __iter__(self): self.num = 1 return self def __next__(self): if self.num > self.max_limit: raise StopIteration temp = self.num self.num += 1 return temp my_integers = Integers(5) my_iterator = iter(my_integers) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator))
Output
2
3
4
5
StopIteration
Creating Infinite Iterators in Python
We can create iterators that never stop iterating. These iterators iterate infinitely without coming to a stop. We do this with the help of a parameter called sentinel.
The function next() raises a StopIteration error when the sentinel value is equal to the iterating value. When we pass a value that will never be equal to the iterating value, the error will never rise and the iteration happens infinitely.
Example of infinite iterators in Python
iter_obj = iter(float, 1) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj))
Output
0.0
0.0
In the above code example, we know that float will never return 1. So we passed 1 to the sentinel. Since 1 and 0 will never be equal, the StopIteration error never rises and iterates infinitely.
Creating Python Custom Infinite Iterators
To create custom iterators that iterate infinitely, all we have to do is not add a condition that raises StopIteration. Since StopIteration never rises, iteration will run forever.
Example of creating custom infinite iterators
class Integers: def __init__(self, max_limit): self.max_limit = max_limit def __iter__(self): self.num = 1 return self def __next__(self): temp = self.num self.num += 1 return temp my_integers = Integers(5) my_iterator = iter(my_integers) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator))
Output
2
3
4
5
6
Advantages of Iterators in Python
The main advantage of iterators is their low memory consumption. While iterating through an object, iterators only store one value at a time in memory. This greatly reduces memory usage thereby increasing the efficiency of our program.
Python Interview Questions on Iterators
Q1. Write a program to create a set_iterator object.
Ans 1. Complete code is as follows:
names = {"Sam", "Smith"} names_iter = iter(names) print(type(names_iter))
Output
Q2. Write a program to iterate over a list without using a loop.
Ans 2. Complete code is as follows:
marks = [69, 86, 100, 90, 93] marks_iter = iter(marks) print(next(marks_iter)) print(next(marks_iter)) print(next(marks_iter)) print(next(marks_iter)) print(next(marks_iter))
Output
86
100
90
93
Q3. Write a program to create a custom iterator that iterates from 1 to 10 in 0.5 intervals.
Ans 3. Complete code is as follows:
class one_to_ten: def __iter__(self): self.value = 1 return self def __next__(self): if self.value > 10: raise StopIteration temp = self.value self.value += 0.5 return temp obj = one_to_ten() obj_iter = iter(obj) print(next(obj_iter)) print(next(obj_iter)) print(next(obj_iter)) print(next(obj_iter))
Output
1.5
2.0
2.5
Q4. Write a program to create an iterator that prints the powers of 2 infinitely.
Ans 4. Complete code is as follows:
class PowersOfTwo: def __iter__(self): self.num = 2 return self def __next__(self): ans = self.num self.num *= 2 return ans two_powers = PowersOfTwo() iter_obj = iter(two_powers) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj))
Output
4
8
16
Q5. Write a program to create an iterator to print English alphabets from A to Z.
Ans 5. Complete code is as follows:
class Alphabets: def __iter__(self): self.unicode = 65 return self def __next__(self): if self.unicode > 90: raise StopIteration temp = self.unicode self.unicode += 1 return chr(temp) alphabets = Alphabets() iter_obj = iter(alphabets) for letter in iter_obj: print(letter, end=" ")
Output
Quiz on Python Iterators
Conclusion
In this article, we learned about iterators in Python. We discussed how to create iterators and how to use the next() function. We also learned the working of iterators and ways to create our own custom iterators. In addition, if you have any questions, please feel free to leave them in the comments area.
Nice simple article, good examples. Appreciate it – thanks!