Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
    ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading