kurious
kurious

Reputation: 1044

Yielding each value from a list

I need to assign each value of a list to a variable. I then call that variable from another program.

This is my code:

inputList = """["vanilla","vanillas","vanill","vanil","vanila"]"""

def singleListSplitter(inputText):
    try:
        inputList = ast.literal_eval(inputText)
        clean_inputList = [item.strip() for item in inputList]

        #print clean_inputList

        for item in clean_inputList:
            yield item
            print item

    except Exception as e:
        print "Error: ",e


singleListSplitter(inputList)

On running the script, I don't see any output in the console with yield. The print works as expected. What do I need to change to get each individual value?

UPDATE 1

Based on the comments and responses, I tried:

value = list(singleListSplitter(inputList))
print value

and got a list in response.

What I want really want here are 5 strings (from the list) that I can use elsewhere.

Upvotes: 0

Views: 54

Answers (1)

jbch
jbch

Reputation: 599

When you use yield in a function, what you have is a generator function.

Generator functions are a bit different from regular function; they do not run when you call them, instead they return a generator object, which is a type of iterator - something you can iterate over, for example in a for loop.

To run the code in the function you need to actually iterate over the generator object.

An easy way to do that is to call list on the generator object.

list(singleListSplitter(inputList))

But if you are not using the values yielded by your function, there is no reason to use yield in the first place, you can just remove it and you'll have a regular function which prints your results.

Upvotes: 1

Related Questions