l=[(“shiv”,20),(“ram”,10),(“sita”,90)]
def key(x):
return x[1]
print(sorted(l,key=key))
How this is working, cant understand the syntax and logic behind it…plz explain briefly.
l=[(“shiv”,20),(“ram”,10),(“sita”,90)]
def key(x):
return x[1]
print(sorted(l,key=key))
How this is working, cant understand the syntax and logic behind it…plz explain briefly.
Hello Shivam, here we have given a list of tuples and it consists of the name as well as the marks. Now if we need to sort the list on the basis of the name
then we can simply use
print(sorted(l))
Then it will return,
l=[(“ram”,10),(“shiv”,20),(“sita”,90)] # As if we see alphabetically ram is smaller than shiv and shiv is smaller than sita
Now suppose you need to sort on the basis of the marks and need to tell the name of the first two students who scored the least among other students then you need to sort on the basis of the marks.
And in that case we pass the function as an argument that compares the value on the basis of the marks and sort on that basis.
So if we do
l=[(“shiv”,20),(“ram”,10),(“sita”,90)]
def key(x):
return x[1]
print(sorted(l,key=key)) # then here in this sorted function we are passing another function key that will tell us on what basis we need to sort the objects
# And then it will output (“ram”,10),(“shiv”,20),(“sita”,90) this time it has sorted don't get confused see the values are in sorted order
And in case of sorted function here we passed x[1] but if we don’t pass anything it assumes it to be x[0] so by default it is x[0] and we don’t need to pass the function in this case else we need some more or diff comparisons then we can pass the key function.
I hope it is clear to you. In case it is clear to you pls mark it as resolve and provide the rating as well as feedback so that we can improve ourselves.
In case there is still some confusion pls let me know, I will surely try to help you out.
Thanks
Happy Coding !!
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.