This article is a part of a 30 day Python challenge series. You can find the links to all the previous posts of this series here:
- 30 Days of Python 👨💻 - Day One - Introduction
- 30 Days Of Python 👨💻 - Day 2 - Data Types I
- 30 Days of Python 👨💻 - Day 3 - Data Types II
- 30 Days Of Python 👨💻 - Day 4 - Data Types III
- 30 Days Of Python 👨💻 - Day 5 - Conditions And Loops I
- 30 Days Of Python 👨💻 - Day 6 - Loops II And Functions
- 30 Days Of Python 👨💻 - Day 7 - Developer Environment
- 30 Days Of Python 👨💻 - Day 8 - OOP Basics
- 30 Days Of Python 👨💻 - Day 9 - OOP Pillars
- 30 Days Of Python 👨💻 - Day 10 - OOP Missing Pieces
- 30 Days Of Python 👨💻 - Day 11 - Functional Programming
- 30 Days Of Python 👨💻 - Day 12 - Lambda Expression And Comprehensions
- 30 Days Of Python 👨💻 - Day 13 - Decorators
- 30 Days Of Python 👨💻 - Day 14 - Handling Errors
Today I explored all about the concept of generators in Python. The concept of generators exists in the JavaScript world as well. It was introduced in the ES6 version of JavaScript however I haven’t used them in practical JavaScript projects much. While reading about them today, I realized they can be of great use and are used in several Python libraries and frameworks.
So what are generators?
A generator is a special kind of function that returns an iterable set of values, one at a time, which means it can be looped over to get the values one by one. It is also sometimes referred to as functions that can be ‘paused’. In theory, generators sound quite complicated and confusing. It is best to explain using code examples. We hare already used a built-in Python generator
range to generate a range of values.- range_of_numbers = range(100) # a generator
- for num in range_of_numbers:
- print(num)
- # Since range is a generator, it can be iterated or looped
- def my_infinite_generator():
- num = 0
- while True:
- yield num
- num +=1
- result = my_infinite_generator()
- for i in result:
- print(i) # Keeps on printing values infinitely!
So what exactly is this generator function and how is it different from a normal function?
Functions can return only one value using the return statement. Once a function reaches a return statement, it returns the value and exits out. Whereas generator functions can return any number of values using a special keyword
yield. Whenever the yield statement is reached, the function execution is paused and the control is passed to the whoever is calling the function.The values of the generator can be extracted either by iteration or by using another built-in function called
next on the generator. In the above block of code, the values of the generator are printed using iteration (for loop). The same can be done manually by using the next function.
Join the conversation! Your thoughts help the community grow.