9

I’m learning about 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? The example says it's “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')]
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
SpicyClubSauce
  • 4,076
  • 13
  • 37
  • 62

1 Answers1

17

You're using a lambda expression (or anonymous function), to sort your list of tuples based on a certain key. pair[1] indicates that you are sorting with a key of the elements in the index position of 1 in each tuple (the strings). Sorting with strings sorts by alphabetical order, which results in the output you are seeing.

Were you to use the first element in each tuple as the sorting key for instance (pair[0]), you would then sort in increasing numerical 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')]
miradulo
  • 28,857
  • 6
  • 80
  • 93