dig_123
dig_123

Reputation: 2358

Lambda function behavior

I'm trying to understand the behavior of the lambda below. What value is actually passing on to argument pair? This will help me understand the return part pair[1].

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

As I understand, sort will sort the list pairs. It will compare if a function is passed as a parameter. So how I'm I getting the below output:

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

Upvotes: 0

Views: 110

Answers (3)

Metropolis
Metropolis

Reputation: 2128

If you want to sort by the numeric value, change your lambda to

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

Python is zero-indexed. The first element of each tuple has index 0. pair[1] would refer to the words in the tuple, not the numbers. So if you want to sort by the text, alphabetically, what you have works.

If you want to see what's being passed through the lambda --- which was your question:

from __future__ import print_function #Needed if you're on Python 2
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: print(pair[1]))

Which returns

one
two
three
four

Verify this by checking the output if you print(pair[0]) or print(pair).

Upvotes: 3

chepner
chepner

Reputation: 531125

Try to avoid lambda expressions where possible. At one point, they were going to be eliminated from the language altogether, and various helper functions and classes were introduced to fill the void that would be left behind. (Ultimately, lambda expressions survived, but the helpers remained.)

One of those was the itemgetter class, which can be used to define functions suitable for use with sort.

from operator import itemgetter
pairs.sort(key=itemgetter(0))

(As @metropolis points out, you want to use 0, not 1, to sort by the initial integer component of each pair.)

Upvotes: 2

Meccano
Meccano

Reputation: 537

The lambda function receives a parameter which in your case is a tuple of size 2 and returns the second element (the number in word format in your case). the sort method will sort your pairs list according to the key you pass to it, which is the lambda function in your code. In python, when sorting a list of strings, it will sort in lexicographically, so your code will sort the pairs in a way that the 2nd elements are sorted lexicographically.

Upvotes: 2

Related Questions