In the tutorial, it was mentioned that we can sort a tuple from the x [ 1 ] index as well by using Lambda function.We assign the value “key=lambda x:x[1]” but when I use some other variable other than "key " then the sorted function doesn’t work
Sorted function using Lambda Functions
‘key’ is the parameter of sorted function. You cannot have any other name for that. Let’s say you have a list:
L = [(1,2), (3,1), (4,-1)]
To sort this list based on second element of tuple. You can either do:
sorted(L, key=lambda el: el[1])
Here el represents each element of the list, which is a tuple. You can use any identifier/ name instead of el, like x, y, z but cannot change the name of the actual parameter of sorted fn which is ‘key’
If you don not want to use lambda expression you can instead create a fn:
def func(x):
return x[1]
Know that here x is the tuple, the element of our list.
Then use sorted fn:
sorted(L, key=func)
HI @rishavraj1808_a240d978fe1ee795 hope your doubt has been resolved… for now I closing this doubt if you still have any isuue please do contact
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.