Member-only story

Memory Efficient Functions with Python Generators in 5 Minutes

With easy to understand examples!

Erdem Isbilen
4 min readJul 20, 2020
Photo by Josie Josie on Unsplash

Generators are special functions that return a lazy iterator which we can iterate over to handle one unit of data at a time. As lazy iterators do not store the whole content of data in the memory, they are commonly used to work with data streams and large datasets.

Generators in Python are very similar to normal functions with some characteristic differences listed below;

  • Generator functions have yield expression, instead of return used in normal functions.
  • Both yield and return statements return a value from a function. While the return statement ends the function completely, yield statement suspends the function by keeping all its state in the memory for later use.
  • When the generator function yields, the function is not terminated. Instead, yield expression pauses the function and gives control over to the caller.
  • After fully iterated, generators terminate and raise stopIteration exception.

This post will introduce you to the basics of generators in Python.

Let’s write a Python3 code that contains simple examples of implementing generators:

# Simple Generator
def

--

--

Erdem Isbilen
Erdem Isbilen

Written by Erdem Isbilen

Machine Learning and Data Science Enthusiasts, Automotive Engineer, Mechanical Engineer, https://www.linkedin.com/in/erdem-isbilen/

No responses yet