0

I have a list like this:

l=[('a',2),('d',0),('c',1),('b',4)]

Now I want to sort it, but by the number, not by the word. If I just use l.sort() it just sorts by alphabetically. My desired output should be sth like (d,0)(c,1)(a,2)(b,4)

I tried l.sort(key = l[0][1]) but it won't work too (l[0][1] actually refer to number 2, which is the second value)

1
  • The key argument expects a callable, i.e. a function that can be applied to every element in l in order to determine its rank compared to other elements. Commented Feb 17, 2022 at 14:47

1 Answer 1

2

You need to pass a lambda as the key that does the right thing:

>>> l = [("a", 2), ("d", 0), ("c", 1), ("b", 4)]
>>> l.sort(key=lambda val: val[1])
>>> l
[("d", 0), ("c", 1), ("a", 2), ("b", 4)]
Sign up to request clarification or add additional context in comments.

6 Comments

Of course you could also pass operator.itemgetter(1) or def get_1(val): return val[1], does not have to be a lambda.
Thank you. I saw people use this lamda thing in some StackOverflow posts before but I didn't understand it. I'm doing some research on this thing right now. Still, may I ask that after "key", it must be a function, right?
A callable, not necessarily a function. operator.itemgetter is a class whose instances are callable. For example, itemgetter(1)(x) is equivalent to (lambda y: y[1])(x).
@chepner but at OP's level it may be less confusing to call everything that's callable a function. At least in this context.
I don't think it's ever too early to emphasize the distinction between functions and callables (or the fact that a lambda expression defines a function, rather than being something special).
|

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.