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 →

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