Lambda expression help

I was reading Python document and I got stuck here. What does lambda do in this code?

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

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Hello @cloud1080432534. lambda is a nameless function. In this case, it sets key to the second element of the argument pair. In this case, it is the second level of iteration in, so pair refers to the tuples within pairs. Here is some reading on lambda function. I think lambdas are also covered in later Python lessons in CC.
I hope this helps!

what I don’t understand is how ‘pair’ refers to the elements inside ‘pairs’ without iteration code written. And pair[1] must refer to pair tuple’s second element but don’t really know how it affects the outcome. Are some codes omitted?

The function is stored in the variable, pairs. pair is the input you’re passing into the function.

There’s also this article in the Analyze Data with Python path that explains it:

1 Like

Here pair is just a parameter for the lambda function. It’s practically equivalent to:

def lambda(pair):
  return pair[1]

Now, the sort function takes a function as an argument for its key parameter. And what it does is it uses that function on each element of the list to sort it. So essentially, it does something like:

for pair in pairs:

The lambda returns the element at index 1 (pair[1]) from each pair and gives it to the sort function, which then sorts the list according to that.

All of that process of applying the key function to every item of the list, and sorting according to it happens in the python list class and specifically its sort method, so it’s already a part of python and there’s no need to write any iteration code yourself to do it, although of course you could if you really wanted to. To find that code you’d have to look inside the python source code, which isn’t written in python.

1 Like

One forgets where I read it, but apparently the latest iterations of Python are moving toward being written in Python. Will need to Google this and try to find the article.

Oh, actually that would be great if it’s so.

1 Like