-1

I have found a code that orders the elements of a list according to the grades specifid in the tuples that constitute the list. I cannot understand how it works though: shouldn't be specified somewhere that the parameter data is referred to the students list? Thanks

students = [("Squidwaard", "F", 60),
        ("Sandy", "A", 33),
        ("Patrick", "D", 36),
        ("Spongebob", "B", 20),
        ("Mr.Krabs", "C", 78)]

grade = lambda data: data[1]
students.sort(key=grade)

for i in students:
    print(i)
Lucky-Luka
  • 13
  • 3
  • It is sorting using data[1] specified in the lambda function I believe. – Richard K Yu Feb 06 '22 at 21:24
  • `data` is just the function argument of the function `grade`. You can define `grade = lambda x: x[1]` and get the same result. In python, a lambda function is no different than a non-lambda function (which is defined using `def`) except that a lambda function is shorter and can be written in one line of code. – Ankur Feb 06 '22 at 21:29
  • Does this answer your question? [python - sorting a sequence with key function](https://stackoverflow.com/questions/50223227/python-sorting-a-sequence-with-key-function) – DarrylG Feb 06 '22 at 21:38
  • "shouldn't be specified somewhere that the parameter data is referred to the students list?" Yes, and it is - by the fact that it's a parameter to the `sort` call. – Karl Knechtel Feb 06 '22 at 21:56

1 Answers1

0

Well here you did specify in your code. You have wrote a function (anonymous) and called in students.sort(key=grade) what key does is use the function given to sort it by. So you are sorting by the 1st index element, which is the letter grade. Hope this helped, have a nice day!

  • Welcome back to Stack Overflow. As a refresher, please read [answer] and avoid conversational language in answers (and questions), as this is *not a discussion forum*. – Karl Knechtel Feb 06 '22 at 23:01