Using Generators inside Functions in Python
Hello everyone, in this tutorial we are going to learn a small trick on how to use generators inside functions in Python. This is a very simple trick and it can come in very handy in problem-solving.
What are generators in Python?
Generators are used to create iterators, but with a different approach. The generators can generate as many as possible values as it wants by yielding each one in this turn. When generators are executed when an iteration over a set of items is started.
Let’s learn this trick
Now let us consider an example where we need to find the sum of the first 100 natural numbers, to do this we would initialize a loop and run it for 100 times and keep on adding each number to the sum variable and another approach to do this is by initialising a list and append all the 100 natural numbers and then find the sum using the sum() function.
The code here would be:
l = [] for i in range (0,100): l.append(i) print(sum(l))
Output:
4950
But then let’s solve this using generator inside the sum function.
print(sum(i for i in range(100)))
Output:
4950 Done, we just did it in one line.
So we successfully able to use generators inside functions in Python.
You guys might be wondering that how is this trick gonna be useful? Well, just imagine a scenario where you are writing a technical round for a company’s hiring process, at that time this trick can come in handy. This trick will not only help you to save abundant code but also helps you by reducing space complexity and can save you time.
Leave a Reply