Need help with yield and send()

I don’t understand the logic behind send() and yield. I am trying to practice with this:

letters = ['A', 'B', 'C', 'D', 'E']

def letter_list():
	for letter in letters:
		x = yield letter
		if x is not None:
			yield x
			
letter = letter_list()
print(next(letter))
letter.send('Q')
print(next(letter))
print(next(letter))

The output I want is
A
Q
C
The output that is given is
A
B
C

I don’t understand why the second iteration is not returning Q. Why is it skipping the code after x = yield letter if the code is supposed to continue after that statement?

Hi Jmm5978,

The send() function is used to send values into a generator that just yielded. Consider the following code:

letters = ['A', 'B']


def letter_list(lst):
    for item in lst:
        item = yield item
        if item is not None:
            yield item


gen = letter_list(letters)
print(next(gen))  # A
print(next(gen))  # B
print(next(gen))  # StopIteration Error

So the generator has no more values; however, you can use the send() function to send another value into this generator like so:

gen = letter_list(letters)
print(next(gen))  # A
print(next(gen))  # B
print(gen.send('C'))  # C
print(next(gen))  # StopIteration Error

Now, to achieve the output that you are looking for simply enclose the send() function in a print statement:

letters = ['A', 'B', 'C', 'D', 'E']


def letter_list():
    for letter in letters:
        x = yield letter
        if x is not None:
            yield x


letter = letter_list()
print(next(letter))  # A
print(letter.send('Q'))  #Q
print(next(letter))  # B
print(next(letter))  #C

Output

A
Q
B
C

Let me know if this helps explain the purpose and use of the send() function. If you have further questions please feel free to ask again!

Best regards,

2 Likes

Thank you. If I understand properly, it went through the iteration as I thought, just did not print that iteration’s yield because I did not remember the print statement?

If I understand properly, it went through the iteration as I thought, just did not print that iteration’s yield because I did not remember the print statement?

Yes, correct!

1 Like