Reputation: 5
list=[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
def st(element):
return (element[1])
print(sorted(list,key=st))
Can someone explain the working of this program? When return statement returns 5,2,4,3,1 to the sorted funtion how do we get the list of tuples sorted ? Instead shouldn't the output be [1,2,3,4,5].Since only the second value returns to the sorted function.
Upvotes: 0
Views: 68
Reputation: 882048
The sorted
function will sort the list (ie, the entire set of tuples) using the function st()
to provide the keys for sorting. The st()
function in no way limits what gets sorted, only what get used to decide how to sort.
You can think of it as you providing an answer to the question the sorted
function needs answered for each element: What is the value for this element I should use when deciding where to put it?
The output is:
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
which is the sorted list using the second item of each tuple to decide order.
Upvotes: 1