Introduction to Iterators and Generators
Introduction to Iterators and Generators
Python is enriched with many powerful concepts that make it a widely popular and loved programming language. Two of these concepts are Python iterators and generators. These concepts are not just confined to Python; they exist in almost all programming languages. In this tutorial, we will dive deep into these concepts and explore their significance in Python.
What is an Iterator?
In Python, an iterator is an object which implements two special methods, namely __iter__()
and __next__()
, collectively known as the iterator protocol.
An iterator object in Python must implement two special methods, which form the iterator protocol.
__iter__()
: This method returns the iterator object itself. This is used in for and in statements.__next__()
: This method returns the next value from the iterator. If there are no more items to return, it should raise StopIteration.
Let's look into a simple example:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
What is a Generator?
Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield
statement whenever they want to return data. Once a generator function calls yield
, it gets paused and the control is transferred to the caller. Local variables and their states are remembered between successive calls.
Here is a simple example of a generator function:
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
for item in my_gen():
print(item)
In the above example, my_gen()
is a generator function as it contains yield
statements.
Difference Between Iterator and Generator
To create an iterator in Python, we need to implement two methods in our iterator class,
__iter__()
and__next__()
. But in the case of generators, we can use theyield
keyword.Generator in python helps us to write fast and compact code. Python iterator is much less memory-efficient.
Generators are a subset of iterators and can be iterated only once. Iterators can be iterated multiple times.
Generators allow
pause
&play
functionality, which is missing in iterators.
In conclusion, both iterators and generators in Python are powerful concepts that can significantly enhance your programming skills. They are used extensively in Python built-in types like lists, tuples, strings, dictionaries, and sets. Understanding them will help you write more efficient and cleaner code.