Tony
Aug 27, 2022

--

One example would be reading large text files, for example let's say you have a 3G csv file, and most people will do the following:

=========

def csv_reader(file_name):

file = open(file_name)

result = file.read().split("\n")

return result

=========

However, you may end up with "MemoryError" since read() just loads everything into memory, the generator version:

========

def csv_reader(file_name):

for row in open(file_name, "r"):

yield row

========

You will not run into memory error as it will not load everything into memory. You can still iterate through the text file content safely.

However, if the text file is small and speed matters more than memory, you still want to use return instead of yield.

--

--

Tony
Tony

Responses (1)