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!
>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:
- https://www.programiz.com/python-programming/list-comprehension
- https://realpython.com/list-comprehension-python/