python programming help

John Ladasky john_ladasky at
Sun Dec 8 20:21:26 CET 2013

On Sunday, December 8, 2013 10:32:31 AM UTC-8, rafae... at wrote:


> def people(age):
>     people=lambda age: [name for name in dic if dic[name]==age]
> people(20)


> this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part.

Well then, don't use it!  It's clear that you are new, and at least you have posted some code now, so let me try to help.

>and this code doesn't give me any result

Right, for TWO reasons.

First problem: if your function does not end with a statement like "return people", the function returns a special Python object called None.

Now, if it were me, I would not "wrap" the calculation of your "people" list inside a "people" function for such a short program.  But this is apparently a requirement of your assignment.  My guess is, in the future, you will write a program that calls the people function multiple times.

The "lambda" word has to do with creating something called an "anonymous one-line function."  You don't need that here.  It's more advanced Python.

What you want to do is compute and, importantly, return a list calculated from your dictionary.  That is accomplished by this expression:

"[name for name in dic if dic[name]==age]"

This is called a "list comprehension."  Do you understand what this does?  It's fairly advanced.  I don't teach list comprehensions to my Python students for the first several lessons.

So, now that you have created the list, let's make sure that Python doesn't lose it.  Let's assign a NAME to it.  By the way, it's probably not good form to use the same name for a function and any of its internal variables.  Pick a different name for your list: for example, "p".  Then, return p from your function to your main program.  My suggested rewrite of your function would be:

def people(age):
    p = [name for name in dic if dic[name]==age]
    return p

The truth is that you can cut this down by even one more line.  This function doesn't need to hold on to the result after it is done returning it, but the computation of the result can be accomplished in one line.  Therefore this will also work:

def people(age):
    return [name for name in dic if dic[name]==age]

OK, that takes care of Problem 1.

Second problem: you call the "people" function with your statement "people(20)", but you don't do anything with the output.  Once you fix the people function by providing a proper return statement, what does the main program do with the output of the function?  Right now, it just throws it away.  

One solution to the problem is to make sure that the function's output gets a name. Try:

result = people(20)

Now, what do you want to do with result?  I will wait to see your answer on that one before I intervene again.

More information about the Python-list mailing list