2

Here's the code:

a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
print max(a,key=lambda w: b[w])

This prints out 1.

I don't understand how max(a,key=lambda w: b[w]) is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by

  1. saving the current value of i as w in the lambda function
  2. getting the corresponding value from b[i] and storing it in key.

But then why does it print out 1 instead of 11? Or why doesn't it print out 10, since that's really the maximum number?

1
  • Almost afraid to ask, but why did you imagine it might produce 11? 1 + 10? Commented Dec 16, 2009 at 20:45

2 Answers 2

9

max(a,...) is always going to return an element of a. So the result will be either 1,2,3, or 4. For each value w in a, the key value is b[w]. The largest key value is 10, and that corresponds with w equalling 1. So max(a,key=lambda w: b[w]) returns 1.

Sign up to request clarification or add additional context in comments.

Comments

-3

Try:

a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
c = a + b.values()
print max(*c)

4 Comments

why is bad? you can also do the same without concatenate the values if a and b are huge.
because it's so far from what OP is trying to do, that it's just frustrating
why the max(*c)? Are you trying to dereference c?
@Goose Bumper: if c refers to [1, 42, 666] then max(*c) is equivalent to max(1, 42, 666) (see http://docs.python.org/reference/expressions.html#calls). My downvote is because that is obscure and inefficient as well; max(c) gives the same result (see http://docs.python.org/library/functions.html#max).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.