In this article, I will take you through the Concepts of Iterator in Python Explained with Best Examples. Iterator is very handy in iterating over the list, tuples, dict, set etc. in python hence it plays an important role in Python Scripting. Iteration is fundamental to data processing – programs mostly apply computations to data series, from pixels to nucleotides. If the data does not fit in memory, we need to fetch the items lazily – one at a time and on demand. That’s what an iterator does. This article shows how the Iterator pattern is built into the Python language so you never need to code it by hand.
Every collection in Python is iterable, and iterators are used internally to support:-
- for loops
- Collection types construction and extension
- Looping over text files line by line
- List, dict, and set comprehensions
- Tuple unpacking
- Unpacking actual parameters with * in function calls
Why Sequences are Iterable
Whenever the interpreter needs to iterate over an object x, it automatically calls
iter built-in function:
- Checks whether the object implements
__iter__, and calls that to obtain an iterator.
__iter__is not implemented, but
__getitem__is implemented, Python creates an iterator that attempts to fetch items in order, starting from index 0 (zero).
- If that fails, Python raises TypeError, usually saying
“C object is not iterable,”where C is the class of the target object.
Iterable vs Iterator
Any object from which the iter built-in function can obtain an iterator. Objects implementing an
__iter__ method returning an iterator are iterable. Sequences are always iterable; as are objects implementing a
__getitem__ method that takes 0-based indexes. It’s important to be clear about the relationship between
iterators: Python obtains
iterables. Check more about Iterator in Python on Fluent Python.
Using Iterator in Python Explained with 3 Best Examples
In python, iterators are objects that can be iterated upon. lists, dictionary, tuples and sets in python are all iterable objects.
All iterator objects uses two exclusive functions. They are:-
iter() -> which is used for initializing iterator object. It internally calls the method
next() -> which is used for iteration i.e iterate all the items of iterator one by one. In python3, we can use
Above two methods are collectively called as
Example 1: Python in-built iterator
mylist= [3,2,4,'Hi'] mystring= 'cyberithub' iterobject1= iter(mystring) iterobject= iter(mylist) print(next(iterobject)) #returns 1 item at a time #print(iterobject.__next__()) # use iterobject.__next__() in python3 for i in iterobject: #iterate complete list right from the next element print(i) for j in iterobject1: print(j)
[root@localhost ~]# python example.py 3 2 4 Hi c y b e r i t h u b
Example 2: Using try-except block in Python
mystring= 'cyberithub' iterobject= iter(mystring) while True: try: print(next(iterobject)) for i in iterobject: print(i) except StopIteration: print("This is the end of list") break
[root@localhost ~]# python example.py c y b e r i t h u b This is the end of list
Python 2. As usual, you should avoid calling special methods directly. Just use the
next(it): this built-in function does the right thing in Python 2 and 3
Example 3: Using Custom build iterators in Python
class Number: def __init__(self, max): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.max>= self.n: result =self.max**2 self.max -= 1 return result else: raise StopIteration ob = Number(6) x = iter(ob) print(next(x)) print(next(x)) for i in x: print(i)
[root@localhost ~]# python3.6 example.py 36 25 16 9 4 1 0