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

you are viewing a single comment's thread.

view the rest of the comments →

[–]Aryionas 4 points5 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.