How does this example lambda function work?

I'm learning lambdas in Python, but I don't understand what's going on in this example.

Can anyone explain what's going on here in plain English? This example says "passing a small function as an argument", but I don't understand what that means.

>>> 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')]



source to share

1 answer

You are using a lambda expression (or anonymous function), sort

your list of tuples based on a specific one key

, pair[1]

indicates that you are sorting with a key of the elements at index position by 1 in each tuple (row). Sorting with strings is sorted alphabetically, resulting in the output you see.

If you were to use the first element in each tuple as a sort key

for example ( pair[0]

), you would then sort in ascending order:

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




All Articles