TheLearningDev's Blog

TheLearningDev's Blog

"yield" keyword in Python

What does the "yield" keyword do in Python?

Bhavani Ravi's photo
Bhavani Ravi
·Sep 23, 2022·

1 min read

Subscribe to our newsletter and never miss any upcoming articles

"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]


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
Share this