How to Write Memory Efficient Loops in Python

Siavash Yasini
Analytics Vidhya
Published in
5 min readJun 30, 2020

--

A visual guide to generators and three ways to implement them

Photo by Tine Ivanič on Unsplash

In python, when you build a list of numbers, images, files, or any other object that you want to iterate through, you’re essentially piling up memory as you put new items on the list, i.e. every time you do your_list.append(new_item) your list consumes a chunk of memory equal to sys.getsizeof(new_item). The problem here is…

--

--

Siavash Yasini
Analytics Vidhya

Ungifted Amateur, Python Enthusiast, Latte Artist, Ex-Cosmologist, Sr Data Scientist @ Fanatics