Two questions/clarifications:
Most people may ask the difference between yield and return.
def square(n): for i in range(n): yield i**2 for i in square(10000000000): print(i)
I understand this is a way to run the 'function' in a generator way. If we directly run print([i**2 for i in range(10000000000)])
or this way
def square():
return [i**2 for i in range(10000000000)]
Python will run almost infinite time. However, if we run in the generator way, we will save a lot of memories, and Python can keep printing the squared numbers. In the generator, we directly print out the result we got and do not save it anywhere. However, in a function-return way, we will save the results into a list so it will waste a lot of memories and time. Am I correct about this?
My another question is yield vs. print: if we want to save memories and hope to directly print out the results, then why don't we just use
print
to directly print out the result, like:def square(n): for i in range(n): print(i**2) square(10000000000)
Python will do the same thing as the yield-generator way, right? So what is the difference between yield and print? Thanks!