cmo cmo - 5 months ago 10
Python Question

Why does yielding an item in a function give different output than printing the item?

I wrote this function to read a list of words representing a number and pair 1-9 digits with multipliers.

def listpairs(element):
pair = []
for word in enumerate(element):
pair.append(word[1])
if word[1] in denoms:
yield pair
pair.clear()
if word[1] in digits and word[0] == (len(element)-1):
yield pair


When I try it with a test string, it gives this:

list(listpairs('two hundred three ten four'.split())
[['four'], ['four'], ['four']]


If I replace yield with print(pair), it gives the expected output:

['two', 'hundred']
['three', 'ten']
['four']


Why does this happen? Is yield the wrong tool here?

Answer

Your are yielding the same list all the time. Replace:

pair.clear()

with:

pair = []

To get new list.

Example:

from string import digits
denoms = ['hundred', 'ten']

def listpairs(element):
    pair = []
    for word in enumerate(element):
        pair.append(word[1])
        if word[1] in denoms:
            yield pair
            pair.clear()
        if word[1] in digits and word[0] == (len(element)-1):
            yield pair

list(listpairs('two hundred three ten four'.split()))

Gives:

[['four'], ['four']]

But:

from string import digits

denoms = ['hundred', 'ten']

‚Äč

def listpairs(element):
    pair = []
    for word in enumerate(element):
        pair.append(word[1])
        if word[1] in denoms:
            yield pair
            pair = []
        if word[1] in digits and word[0] == (len(element)-1):
            yield pair


list(listpairs('two hundred three ten four'.split()))

Results int:

[['two', 'hundred'], ['three', 'ten']]
Comments