Iterators in Python
Iterators in Python
In Python, iterators are objects that can be iterated upon and loops can be used to access each element of the iterator. Lists, tuples, sets, dictionaries, strings, etc are various forms of iterables available in Python and can be converted into iterator form. An iterator object must implement following methods in Python:
- __iter__(): to initialize an iterator which means to fill it with some values.
- __next__(): to return next element from the iterator and perform some operations on it.
Example:
# Python program to exemplify use of iter and next function of iterator object List = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] Iter = iter(List) print(next(Iter)) print(next(Iter)) print(next(Iter)) print(next(Iter)) print(next(Iter)) print(next(Iter)) print(next(Iter))
In the program provided above, a list named “List” is created with 7 elements. Method iter() function is then used to convert the created list into an iterator so that next() function can be used on it. Method next() is used seven times since iterator has 7 elements and they are then displayed using the print() method.
Output:
MON TUE WED THU FRI SAT SUN
Create an Iterator in Python
A user-defined iterator can be created in Python. It is created using the functions __iter__() and __next__(). To initialize the iterator, __iter__() function is used. To obatin next element from the iterator, __next__() function is used.
Example:
# Python program to exemplify creation of an iterator class IterClass: def __iter__(self): self.var = 1 return self def __next__(self): x = self.var self.var += 1 y = x ** 3 return y IterObj = IterClass() Iter = iter(IterObj) for i in range(1, 11): print(next(Iter), end=" ")
In the program provided above, a class named “IterClass” is created with two functions: __iter__() and __next__() to make it an iterator. Method __iter__() is used to initialize the iterator along with the element var. Method __next__() is used to perform operations on the element var and return it. A for loop is used on a range of 1 to 10 which calls next() method of the iterator object.
Output:
1 8 27 64 125 216 343 512 729 1000
StopIteration
StopIteration statement is used to stop the iteration at some desired point in the __next__() function. A terminating condition can be used inside the __next__() method to raise StopIteration error.
Example:
# Python program to exemplify use of StopIteration statement class IterClass: def __iter__(self): self.var = 1 return self def __next__(self): if self.var < 6: x = self.var self.var += 1 y = x ** 3 return y else: raise StopIteration IterObj = IterClass() Iter = iter(IterObj) for i in range(1, 11): print(next(Iter))
In the program provided above, a class named “IterClass” is created with two functions: __iter__() and __next__() to make it an iterator. Method __iter__() is used to initialize the iterator along with the element var. Method __next__() is used to perform operations on the element var and return it. It does the cube of the number and returns it as long as the variable var is less than 6. If not, then StopIteration error is raised. A for loop is used on a range of 1 to 10 which calls next() method of the iterator object.
Output:
1 8 27 64 125 Traceback (most recent call last): File "main.py", line 21, in <module> print(next(Iter)) File "main.py", line 15, in __next__ raise StopIteration StopIteration