Doubt with the lambda function

what does the fun #key=lambda x:x[i]) in
sorted(a,key=lambda x:x[i]) mean
and how is it comparing the elements of the list ‘a’

Syntax for sorted() is-
sorted(iterable, key, reverse)

In this key is a function that would serve as a key or a basis of sort comparison.

In the lambda function we are taking in as an argument a tuple which is inside the list , i.e, (“jatin”,5)
and then (“prateek”,10) and so on, this is accessed by x.
We can also say that it is taking in as arguments the elements present in the list itself item by item .
It is occuring with the help of x without even specifying the list ‘a’ because it uses the iterable passed in sorted() itself and uses its elements .
Now by writing x[1] we are accessing the element present at index 1 of each tuple , which are 5 then 10 and so on.
So in lambda function we are basically returning the scores present in each tuple.Hence our sorting will be done on the basis of these returned values(scores) itself.

1 Like

ohk understood the concept