"yield" keyword in Python
What does the "yield" keyword do in Python?
Table of contents
"yield" is a Python keyword that can be used in a function instead of return.
def scale_vector(vector, n):
return [return v*n for v in vector]
vs
def scale_vector(vector, n):
for v in vector:
yield v * n
The first scale_vector
returns a list, whereas the second one returns a generator which gets computed at runtime
Why use "yield" when you can use "return"?
Let's say you have to scale an array of 1 Lakh records, you don't have to have them all loaded into the memory simultaneously. You can read and process one after the other.
def get_lines(file_path):
for f in files:
for line in f:
yield line
def scale_vector(file_path, n):
for line in get_lines(file_path):
yield int(line) * n
Yeild From
In the above example see how we have looped through get_lines
yeild again. That is kind of redundant. To work around this Python provides us with a sweet syntax combining yeild
and from
def get_lines(file_path):
for f in files:
for line in f:
yield line
def scale_vector(file_path, n):
yeild from get_lines(file_path):
ย