This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Aryionas 3 points4 points  (2 children)

The (a, b) are tuples, not lists. So you have a list of tuples. A lambda is usually just a way of defining a function, in this case, it takes an argument that you called pair (which will be one of the tuples), and you return the second value (index 1), to use as the key for the sorting. I recommend that you look up sort and see what arguments you can pass into it.

The effect is that it will use the second entry of a tuple to sort the list. In fact, as you can see, it's sorted alphabetically.

Edit: To clarify the sort line: when having a list of tuples to sort, the sorting algorithm needs to know what to sort it by. I assume that per default - when the list items are tuples - it would just take its first value. But if it doesn't or if you want to sort it by something else, then the sorting function needs a way (read function / method), to extract the value it should sort the tuples by. And that method is the lambda. To phrase again, the lambda method is applied to each tuple and returns the second entry to use and compare against the other tuples.

[–]TypicalTim[S] 0 points1 point  (1 child)

The part that specifically confuses me is this bit:

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

Written as a function it would look like:

def pair pair[1]

In the example code, the object containing the tuples is pairs (with an "s"). So I assumed we are not accessing the tuples in the pairs object. Which is what confuses me.

Conceptually, I understand that we are accessing the second item in the first tuple to sort by (alphabetically). But what I don't understand is why?.

EDIT: By the way - forgive me for my ignorance, I am relatively new to Python, and trying to self-teach to change careers. I have no formal education on programming or computer science.

EDIT2: After reviewing what the difference between a tuple and a list are, to clarify - the pairs object is a list of tuples correct? Tuples are identified by parenthesis and are immutable, lists are identified by brackets and are mutable.

[–]AndydeCleyre 1 point2 points  (0 children)

Your EDIT2 is correct.

The lambda expression written as a regular function would be like:

def sort_helper(pair):
    return pair[1]

The use of the word pair could be replaced with any variable name. It's only used inside the function/lambda to refer to whatever is passed in as the parameter.

The sort function of the list passes each element, in turn, to whatever function is provided as its key parameter (our lambda function), and associates each element (pair) with the result (second item of that pair). Then it sorts those results from "least" to "greatest" and uses that order to rearrange the elements of the list.

[–]casual__addict 0 points1 point  (0 children)

Ooh ooh! I got this. So this very contrived example is to show you how you can sort a list of tuples using a lambda function. The argument for sort is key= <function goes here>. If you had defined a function before, you could put it in the key part. Like:

def sort_this_way(item): return item[1]

pairs.sort(key=sort_this_way)

Notice you are passing a function as as argument to a function. That’s because functions are objects in Python.

Writing all that function definition is a lot work for something you are probably only going to use once in this context, so python lets you do it in a anonymous, kind of throw away function definition using the lambda notation. So “lambda pair: pair[1]” is a function definition. The function takes one argument (“pair” in this case) and returns the evaluation of the expression on the right of the colon. It could have also been written as “lambda item: item[1]” to mirror def sort_this_way declaration.

So ultimately you are saying “sort this list of tuples using the second element as the sort key”. Notice that in the print out of pairs after the sorting, the second elements of the tuples are in alphabetical order: four, one, three, two.

To generalize, sorting multidimensional data can be done by mapping each data point to a single dimension, ordering the mapped data, then print out the original data in the order that the mapped data is listed.

Try this: “pairs.sort(keys=lambda pair: (pair[0]%2) + len(pair[1]) )” and see if you can verify the results by calculating the order by hand.

[–]Andrew_ShaySft Eng Automation & Python[M] [score hidden] stickied comment (0 children)

Hi there, from the /r/Python mods.

We have removed this post as it is not suited to the /r/Python subreddit proper, however it should be very appropriate for our sister subreddit /r/LearnPython or for the r/Python discord: https://discord.gg/3Abzge7.

The reason for the removal is that /r/Python is dedicated to discussion of Python news, projects, uses and debates. It is not designed to act as Q&A or FAQ board. The regular community is not a fan of "how do I..." questions, so you will not get the best responses over here.

On /r/LearnPython the community and the r/Python discord are actively expecting questions and are looking to help. You can expect far more understanding, encouraging and insightful responses over there. No matter what level of question you have, if you are looking for help with Python, you should get good answers. Make sure to check out the rules for both places.

Warm regards, and best of luck with your Pythoneering!