2

In a tutorial, I see a piece of code that I verified works: https://wiki.python.org/moin/HowTo/Sorting

>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Why is the student[2] known by python to refer to the third element of each tuple? Why didn't it try to sort by the third tuple, instead of the third item of each tuple?

3
  • 1
    because it iterates over the iterable passing each subelement, on a side note operator.itemgetter(2) would be more efficeint Commented Jul 7, 2015 at 13:10
  • why is that, does that one run faster? Commented Jul 7, 2015 at 13:20
  • 1
    yes itemgetter is done at the c level, a lambda is more expensive, it depends on what you want to do as there are some things you can do with a lambda that itemgetter cannot do but for your example itemgetter would be more efficeint Commented Jul 7, 2015 at 13:38

1 Answer 1

2

Because sorted function sends the elements of its iterable argument to lambda function.and in this case the tuples will be sent to lambda.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

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

2 Comments

so that's why key has to take a function
@codyc4321 Indeed, you want to sort the elements not the list ;)

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.