From this tutorial, you will be learning about Python Iterator. You will see how to use built-in iterators with lists, tuples, also to implement them using classes.
Note: The syntax used here is for Python 3. You may modify it to use with other versions of Python.
To Learn Python from Scratch – Read Python Tutorial
What is Python Iterator?
An iterator is a container object that holds multiple values and provides a mechanism to traverse through them. Examples of inbuilt iterators in Python are lists, tuples, etc. We can use them to implement “for” loops, generators, etc.
The Python iterator object implements Iterator Protocol. It provides two methods, i.e., they are __iter__ and __next__.
__iter__() gets you an iterable object whereas with the __next__ method you can iterate over the object’s content.
How does Iterator work in Python?
Most of the time, you have to use an import statement for calling functions of a module in Python. However, iterators don’t need one as you can use them implicitly.
When you create an object, you can make it iterable by calling the __iter__ method over it. After that, you can iterate its values with the help of __next__ method. When there is nothing left to traverse, then you get the StopIteration exception. It indicates that you’ve reached the end of the iterable object.
The for loop automatically creates an iterator while traversing through an object’s element.
The following flowchart attempts to simplify the concept for you.
Python Iterator Syntax
To use iterators, you can use the methods as defined above __iter__ and __next__ methods.
The syntax to create an iterable object is as follows:
iterable_object = iter(my_object_to_iterate_through)
The syntax to iterate through the values of an object is:
iterable_object = iter(my_object_to_iterate_through) next(iterable_object)
Creating an iterable object of Tuple:
Cubes = (1, 8, 27, 64, 125, 216) cube = iter(Cubes) print(next(cube)) print(next(cube))
Creating an iterable object of List:
Negative_numbers = [-1, -8, -27, -64, -125, -216] Negative_number = iter(Negative_numbers) print(next(Negative_number)) print(next(Negative_number))
Iterating through an empty object:
List =  empty_element = iter(List) print(next(empty_element)) print(next(empty_element))
Traceback (most recent call last): File "C:\Users\porting-dev\AppData\Local\Programs\Python\Python35\test11.py", line 3, in <module> next(empty_element) StopIteration
Iterating a non-existent object:
List = [1,2,3,4] empty = iter(List) print(next(empty)) print(next(empty))
Printing a list of natural numbers:
The below example provides a script that can get called or executed in the interpreter shell.
Please be careful about the indentation blocks when you enter the code in interpreter shell.
class natural_numbers: def __init__(self, max = 0): self.max = max def __iter__(self): self.number = 1 return self def __next__(self): if self.max == self.number: raise StopIteration else: number = self.number self.number += 1 return number numbers = natural_numbers(10) i = iter(numbers) print("# Calling next() one by one:") print(next(i)) print(next(i)) print("\n") # Call next method in a loop print("# Calling next() in a loop:") for i in numbers: print(i)
To execute the above code use the command python3 /path_to_filename depending upon the default python version used.
# Calling next() one by one: 1 2 # Calling next() in a loop: 1 2 3 4 5 6 7 8 9
We wish the above Python Iterator tutorial would have given you a fair idea of using them in real Python programs.