I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
This bit of code returns
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
So in line one, it defines pairs with a list of different tuples. I get that. Line two is where I'm completely thrown off and I've done quite a bit of messing around with it to try to understand what's happening.
I've found that sort() is applying a built-in function to the variable pairs, and presumably it is sorting it per the instructions I'm giving it.
The sort() function requires a key, and key has to be defined using a function, hence the use of lambda. I think all of this is correct, but I may be way off here.
Lambda defines a new parameter, "pair" on the left side of the colon, and on the right side is the calculation to define the return value of the lambda function.
That's where I'm thrown off. What does "pair[1]" do? What is its affect on the "pair" on the left side of the colon?
What value does it return? I can't seem to get it to return any sort of value outside of coding it just like this.
I'm guessing that it somehow points to a specific tuple and sorts it based on repositioning that, but I'm not sure of the logic behind that.
Can anyone explain this for me? Thank you.
lambdayou reference on values that you need to sort by.key = lambda pair: pair[1], then calledkey(pairs[0])and compared that to, say,key(pairs[1])? What if I told you the end result is sorted alphabetically on the second element of each tuple?