4

From the Python documentation regarding using lambdas with the sort method:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] 

So looking for a sanity check to confirm I’m understanding this correctly: The lambda in this example takes in a pair (in this case, a tuple,) and sorts on the 2nd element (or the 2nd value; I’m not sure of nomenclature) of the tuple.

Since the 2nd element is a string, the sort surfaces ‘alphabetically inferior’ values to the top. Thus, the output has tuples with alphabetically inferior 2nd elements at the top of the collection.

Is my understanding correct?

Steve Boniface
  • 571
  • 1
  • 11
  • 23

2 Answers2

1

That's correct.

The key function is called on each value in the list you're sorting, and the sort order is based on the result of that call. Strings naturally sort lexicographically ("alphabetically" as you put it) and list.sort sorts ascending by default, so you'll get the list of all tuples in the ascending lexicographic order of their second element.

Note that this is more commonly done by using the operator.itemgetter convenience function.

from operator import itemgetter

my_list.sort(key=itemgetter(1))
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • I like your answer, although you're using `more commonly` pretty loosely here, I see many people use lambda for cases like this and the reason you want to use itemgetter is due to the fact that the lambda is called for every iteration thus defining a new function every iteration in turn being slower. [see here](https://stackoverflow.com/questions/17243620/operator-itemgetter-or-lambda/17243726) – Jab Feb 09 '19 at 03:42
  • @Jaba `itemgetter` is faster, clearer, more functional, and in wide use. I'm not sure what your nitpick means? In my experience, `itemgetter` (for all those reasons) is more commonly used than a one-shot lambda. – Adam Smith Feb 09 '19 at 03:46
  • 1
    You are right, I guess this was more of a nitpick on how commonly I've seen people using lambda for such tasks. Wasn't picking a fight, I guess it was more a comment for OP. – Jab Feb 09 '19 at 03:52
0

Yes, sanity confirmed. It sorts on the second element of each pair.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578