I'm having trouble understanding the yield
keyword.
I understand the effects in terms of what happens when the program gets executed, but I don't really understand how much memory it uses.
I'll try to explain my doubts using examples.
Let's say we have three functions:
HUGE_NUMBER = 9223372036854775807
def function1():
for i in range(0, HUGE_NUMBER):
yield i
def function2():
x = range(0, HUGE_NUMBER)
for i in x:
yield i
def function3(file):
with open(file, 'r') as f:
dictionary = dict(csv.reader(f, delimiter = ' '))
for k,v in dictionary.iteritems():
yield k,v
Does the huge range actually get stored in memory if I iterate over the generator returned by the first function?
What about the second function?
Would my program use less memory if I iterated over the generator returned by the third function (as opposed to just making that dictionary and iterating directly over it)?