0
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])

print(pairs)

Ans:

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

How does the pair argument work here?

4
  • 3
    Do you understand what the key argument to sort does? Have you read the documentation? What specifically are you asking about? Commented Oct 18, 2017 at 16:22
  • FWIW, it would be better to use key=operator.itemgetter(1) Commented Oct 18, 2017 at 16:27
  • 1
    Something like mapping def something(pair): return pair[1] over each item in the list. It's not clear which part you're unsure about. The word "pair" itself has no specific meaning, call it whatever you like. Commented Oct 18, 2017 at 16:28
  • @roganjosh get it Commented Oct 19, 2017 at 6:39

1 Answer 1

2

When you want to sort a collection, the key parameter is a function that is used to extract from each element the value by which you want to sort. The function takes the argument, produces a value, and uses this value to sort the list

In your case, lambda pair: pair[1], is just an anonymous function that takes your (x, y) pairs of values and returns only the y. Since those values are strings in your case, your list is sorted in alphabetical order of the second value of each tuple.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.