Home > Software design >  What is the relationship between sorted and lambda
What is the relationship between sorted and lambda

Time:06-08

Can someone help me to understand this code please:

tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))
tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1]))
print(tuple1)

CodePudding user response:

sorted is a function which can sort a list according to some criteria. The criteria can be customized by passing a function as the key parameter.

lambda is a way to define a function. So it can be used to specify the criteria for sorting.

CodePudding user response:

Quoting the docs for sorted

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

  • Related