Skip to content Skip to sidebar Skip to footer

Python: Return List Result Problem In A Function

If I do this with print function def numberList(items): number = 1 for item in items: print(number, item) number = number + 1 numberList(['red', 'oran

Solution 1:

return ends the function, while yield creates a generator that spits out one value at a time:

def numberList(items):
     number = 1for item initems:
         yieldstr((number, item))
         number = number + 1

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

alternatively, return a list:

def numberList(items):
     indexeditems = []
     number = 1for item initems:
         indexeditems.append(str((number, item)))
         number = number + 1return indexeditems

item_lines = '\n'.join(numberList(['red', 'orange', 'yellow', 'green']))

or just use enumerate:

item_lines = '\n'.join(str(x) for x in enumerate(['red', 'orange', 'yellow', 'green'], 1)))

In any case '\n'.join(str(x) for x in iterable) takes something like a list and turns each item into a string, like print does, and then joins each string together with a newline, like multiple print statements do.

Solution 2:

A return function will return the value the first time it's hit, then the function exits. It will never operate like the print function in your loop.

Reference doc: http://docs.python.org/reference/simple_stmts.html#grammar-token-return_stmt

What are you trying to accomplish?

You could always return a dict that had the following:

{'1':'red','2':'orange','3':'yellow','4':'green'}

So that all elements are held in the 1 return value.

Solution 3:

The moment the function encounters "return" statement it stops processing further code and exits the function. That is why it is returning only the first value. You can't return more than once from a function.

Post a Comment for "Python: Return List Result Problem In A Function"