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

Python 3 Exercise: What's the difference between these two?

I’m working on a python exercise. This block of code is confusing me.

Here’s what I wrote:

def available_on_night(gamers_list, day):
    for gamer in gamers_list:
        if day in gamer['availability']:
            return gamer

My code only returns the info of one available guest which is not what I want.

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

The provided answer is written using only one line of code, and does return all available guests’ info. Here it is:

def available_on_night(gamers_list, day):
    return [gamer for gamer in gamers_list if day in gamer['availability']]

What’s the difference between my code and the provided answer? If choosing not to write everything in one line, what changes should I make to my code? Thank you!

>Solution :

The answer, simplified, is this:

result_list = []
for gamer in gamers_list:
    if day in gamer['availability']:
        result_list.append(day)

return result_list

The difference is that the solution returns a list, while you stop the program by directly returning the first value. When writing return, you get out of the function. Try storing the values inside a list and return the list at the end of the function.

I suggest reading the following articles on list comprehensions:

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