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

Time:08-01

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.

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!

CodePudding user response:

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:

CodePudding user response:

I'll keep it simple, you're only returning one item that matches. Instead keep a list of items and return them at the end of your for loop.

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

Use the list comprehension though, avoid unnecessary variables.

Hope this helped :)

  • Related