what are iterators generators and decorators in python?

In this post you will learn, what are Iterators Generators And Decorators In Python. Also, we will discuss about their implication and the reasons of their usage. I hope you will like the article 😀

What are Iterators?

An Iterator is an object which can be iterated upon which means it can explore all values one by one. You can think of it as an object which holds more than one value and their value can be iterated (printed or used) one by one is called an iterator. For example lists, tuple, sets, dictionary, etc. are all examples of iterators.

To create an iterator object you have to implement the two methods __iter__() and __next__() to your object. These methods are collectively called Iterator protocol.

__iter__() method is called by iter() function, which returns the iterator object itself. This iterator object then can be used with for loop or in statements

__next__() method returns the next value of the iterator. If there is no more value to return, the StopIteration exception will be raised.

Iterators Generators and decorators in python

Example of Iterator

So, we look at a simple iterator example with a for loop, first we will create a list which is an iterator object, then inside a list we will call next() function to get the all values of the list one by one.

Behind the scenes, this for loop actually creates an iterator object by calling the iter() function on our iterable object. 

# create an iterator object from that iterable
iter_obj = iter(iterable)

# infinite loop
while True:
    try:
        # get the next item
        element = next(iter_obj)
        # do something with element
    except StopIteration:
        # if StopIteration is raised, break from loop
        break

Also for loop iterator is ironically an infinite while loop which calls next() function to retrieve the next element and uses this value to run the body of the for loop. When all of the elements have been exhausted, StopIteration is raised, which is internally caught, and the loop terminates. It should be noted that any other type of exception will be ignored.

How to create your custom Iterator

In this section we will see how you can create your own custom iterator from scratch. For this example you will be required to have some knowledge about Python Object oriented programming. 

So, for the demonstration, we will create a simple iterator that will return all values between the given range. Also, Keep in mind that an iterator object can only be used once. It indicates that after raising StopIteration once, it will continue to raise the same exception.

Why do we use iterators?

Iterators let us build and deal with lazy iterables, which means you can utilise an iterator for lazy evaluation. This allows you to access the next member of the iterator without recalculating all of the previous elements. Iterators can save us a significant amount of memory and CPU time.

Python includes numerous built-in classes that are iterators, such as enumerate, map, filer, zip, and reversed, among others.

What are Generators? 

The generator function is used to simplify the process of creating an iterator, it is a quick and easy technique to create iterators. All of the work stated above is done automatically via Python generators.

Generator functions behave exactly like ordinary functions, with the exception that they utilise the Python yield keyword instead of return and a generator function’s output is an iterator. And the returned output can be used with either next() function or with for loop.

How to create a Generator 

In Python, creating a generator is a very easy task. It’s the same as defining a regular function, but you use a yield statement instead of a return statement.

A function becomes a generator function if it contains at least one yield statement (it may also have other yield or return statements). Yield and return will both return a value from a function.

The distinction is that a return statement stops a function completely, but a yield statement stops the function while storing all of its states and then continues from there on subsequent calls.

What is generator expression?

Just like lambda function Generator expression creates an anonymous iterator, and its syntax is like list comprehension with the exception that it uses parenthesis (round bracket) instead of a square bracket. 

The main difference between generator expression and list comprehension is that, unlike list comprehension which outputs a list with its result, generator expression outputs an iterator that can be used with the next() function and for loop.

Decorator

A decorator is used to manipulate pre-existing functions or their output (by adding, deleting, or altering characteristics). It takes a function as input, modifies it, and returns it. This is also known as metaprogramming since a portion of the program attempts to alter another portion of the program during the compilation process.

What is

Iterators Generators and decorators in python, decorator in python, generator expression python, iterators in python, Iterators Generators and decorators in python, decorator in python, generator expression python, iterators in python, Iterators Generators and decorators in python, decorator in python, generator expression python, iterators in python,

What is a decorator and how to use it

Read more about decorator from here, also I have included a free notebook for your decorator practice there, you can download that if you want.

So, this was all about iterators generators and decorators in python I hope you like this article, if you did then pls share share it with your friends. Also if you want to learn more about it then you can visit here

cropped Bug logo 1 iterators generators and decorators in python,iterators in python,generator expression python,decorator in python

Data Scientist with 3+ years of experience in building data-intensive applications in diverse industries. Proficient in predictive modeling, computer vision, natural language processing, data visualization etc. Aside from being a data scientist, I am also a blogger and photographer.

Share this post

Read next...

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments