Python: Return list result problem in a function

22,044

Solution 1

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

def numberList(items):
     number = 1
     for item in items:
         yield str((number, item))
         number = number + 1

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

alternatively, return a list:

def numberList(items):
     indexeditems = []
     number = 1
     for item in items:
         indexeditems.append(str((number, item)))
         number = number + 1
     return 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.

Share:
22,044
Kolly Boy
Author by

Kolly Boy

Updated on September 17, 2020

Comments

  • Kolly Boy
    Kolly Boy over 3 years

    If I do this with print function

    def numberList(items):
         number = 1
         for item in items:
             print(number, item)
             number = number + 1
    
    numberList(['red', 'orange', 'yellow', 'green'])
    

    I get this

    1 red
    2 orange
    3 yellow
    4 green
    

    if I then change the print function to return function I get just only this:

    (1, 'red')
    

    why is this so?

    I need the return function to work exactly like the print function, what do I need to change on the code or rewrite...thanks...Pls do make your response as simple, understandable and straight forward as possible..cheers

  • Kolly Boy
    Kolly Boy over 12 years
    I understand that, what I want is stated in my question
  • agf
    agf over 12 years
    This doesn't help him with how to do it.
  • mal-wan
    mal-wan over 12 years
    What you want is impossible unless you capture all elements in the 1 return object as I suggested or use yield as agf suggested. A return statement ends a function - it can't return multiple times.
  • djhoese
    djhoese over 12 years
    +1 for mentioning enumerate and your appending to a list solution (that's how I was going to answer it).