-7

Please be gentle I'm still learning Python. I've an example where

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

pairs.sort(key=lambda pair: pair[1])

The result is

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Can you please help explain why this is the sequence?

Milky
  • 1
  • A `lambda` is an anonymous function: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions – UnholySheep Jan 03 '19 at 15:15
  • `lambda` is the same as an unnamed function, i.e. `def f(pair): return pair[1]`. You will do well to brush up on the vast documentations and tutorials on beginner basics of Python before venturing further... – r.ook Jan 03 '19 at 15:15
  • 1
    Give [this](https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda) post a look – yatu Jan 03 '19 at 15:16
  • *All* functions are anonymous; the `def` statement simply binds the function to a name after it has been defined. A `lambda` expression is an expression (rather than a statement) that can create a function as long as the body of the function is itself a single expression. – chepner Jan 03 '19 at 15:16
  • Adding to what was already said : you are establishing a criteria on how to sort. The lambda function returns the second element for each tuple. Therefore, you are sorting by the second element of your tuples. – Matina G Jan 03 '19 at 15:18
  • There is an incredible pletora of materials on Python Lambda functions, so I suppose that here the issue is not really 'what a lambda is'. Maybe the keyword arguments in the `sort` function may be misleading: it does not contain the key _attribute_ upon which sorting, but the _function_ that extracts the key that will be used for sorting. That function is thus invoked on each element of the list. – fcracker79 Jan 03 '19 at 15:18
  • Aha! The sorting is alphabetical from the second element! Sorry to bother you nerds, like I said please be gentle to anyone who wants to learn. – Milky Jan 03 '19 at 15:23

1 Answers1

0

A lambda is simply a short way of declaring a simple function. That code could just as easily have been written:

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

def key_func(pair):
    return pair[1]

pairs.sort(key=key_func)

In this case, the lambda function is telling sort how it should turn a value in the array (in this case, a tuple which doesn't have an obvious sorting order) into a value that it knows how to sort (a string).

Harry Cutts
  • 1,352
  • 11
  • 25