Difference between yield and yield from in Python

The PEP 255 introduced generators in Python. The yield keyword is normally used with generators. This article will discuss the difference between “yield” and “yield from“.

The yield statement

The generator is a function that returns an iterator. Normally a generator function has a yield statement. To define a generator function we need to use a yield statement as shown below:

def generate_number():
  for x in range(10):
    yield x

The generate_number has a yield statement, so it is a generator function. Let’s print the values from the generator :

gen = generate_number()

for number in gen:
  print(number)

Output

0
1
2
3
4
5
6
7
8
9

The “yield from” statement

The “yield from” allows us to yield from another generator function or iterables. Let’s understand with some examples.

Consider the following generator function :

def gen_number():
  yield 1
  yield 2
  yield 3

We can print the generator values using a loop.

for num in gen_number():
  print(num)

Output

1
2
3

Let’s consider another function(gen_cool_numbers) using the gen_number generator function.

def gen_cool_numbers():
  yield 1000
  for num in gen_number():
    yield num
  yield 2000

for x in gen_cool_numbers():
  print(x)

Output

1000
1
2
3
2000

We can update the gen_cool_numbers function by replacing the for loop with yield from as shown below:

def gen_cool_numbers():
  yield 1000
  yield from gen_number()
  yield 2000

for x in gen_cool_numbers():
  print(x)

Output

1000
1
2
3
2000

Yield from can also be used with iterable(list, tuple, string etc)

def gen_cool_numbers():
  yield 1000
  yield from [50,60,80]
  yield 2000

for x in gen_cool_numbers():
  print(x)

Output

1000
50
60
80
2000

Conclusion

The “yield” keyword is used to create a generator function but the “yield from” keyword is used to yield the values from another generator function or iterables.