return statement just prints one value, print statement prints all the values

Question:

I have this method:

def filter_verdi_total_fruit_cost(file_name):
    output = []
    for token in file_name.split('n'):
        items = token.split()
        if len(items) > 2 and items[1] in fruit_words:
            output.append((items[1], items[-1]))
            for _, v in output:
                return v

print(filter_verdi_total_fruit_cost(verdi50))

And it prints just one value: 123,20.

But when I replace return v with: print(v) it prints all the values, when I am calling the method: print(filter_verdi_total_fruit_cost(verdi50))

123,20
2.772,00
46,20
577,50
69,30
3.488,16
137,50
500,00
1.000,00
2.000,00
1.000,00
381,2

But this I don’t understand. I just return v. and then it prints just one value. If I do a print(v) it prints all the values.

Question: How can I return all the values in the method, without the print statement?

Asked By: mightycode Newton

||

Answers:

When you invoke the returnstatement, your function is stopped and returns a value.

You can print the elements outside the function like this, returning the array with all the tuples.

def filter_verdi_total_fruit_cost(file_name):
    output = []
    for token in file_name.split('n'):
        items = token.split()
        if len(items) > 2 and items[1] in fruit_words:
            output.append((items[1], items[-1]))
    return [v for _, v in output]

print(x for x in filter_verdi_total_fruit_cost(verdi50))
Answered By: Rodrigo Guzman

To return all the values in output as a list, change this:

            for _, v in output:
                return v

to this:

    return [v for _, v in output]

Note that it needs to be outside of the for loop (i.e. de-indented to the same level as output = []) so that it won’t happen until you’ve finished building the entire output list.

You could also write this as a list comprehension rather than appending to a list, e.g.:

def filter_verdi_total_fruit_cost(file_contents):
    return [
        items[-1] for items in (
            token.split() for token in file_contents.split('n')
        ) if len(items) > 2 and items[1] in fruit_words
    ]
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.