1

Can someone explain that the importance of lambda in this format of sorting tuples? Further, what exactly does each element of this sorting method mean?

sorted(authorlist, key = lambda tup: tup[0], reverse = True)

I know that reverse = True allows for the list of tuples to be sorted in decending order, the tup[0] indicates what index you want to sort by, and that the first parameter is the tuple/list, but what does key = lambda mean and why is tuple referred to as tup?

Thanks!

Puneet
  • 615
  • 2
  • 7
  • 17
Anam Shah
  • 11
  • 1
  • 1
    From the docs for `sorted`: _"`key` specifies a function of one argument that is used to extract a comparison key from each list element"_. So the lambda here is the one argument function. – miradulo Apr 16 '18 at 04:20
  • Please read about the `lambda` feature in the official language tutorial: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions and the documentation for the `sorted` function: https://docs.python.org/3/library/functions.html?highlight=sorted#sorted and try again if you have a more specific question. "Please help me understand this code" is usually not a good question for SO. – Karl Knechtel Apr 16 '18 at 04:22

1 Answers1

1

lambda is just a syntax shortcut to put a function as a parameter without defining it explicitly on the lines above. Lambdas are restricted Lambdas are restricted to a single expression. So for longer functions you do have to define them separately

The code above could be re-written as

def getKey():
   return tup[0]

sorted(authorlist, key = getKey, reverse = True)

This code is functionally equivalent to the one you posted in the question. The purpose of lambda is to extract the first field from the tuple that you are sorting.

Vlad
  • 9,180
  • 5
  • 48
  • 67