How to use sort method for sorting list in Python?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to use sort method for sorting list in Python??

Python

30th Mar 2019, 12:34 PM
ANU
ANU - avatar
3 Answers
+ 7
In the simplest way, it can be used as myList.sort() With no parameters. It'll by default sort the list in the ascending order. To sort in descending order, you need to make its reverse parameter as True. myList.sort(reverse=True) It can also take a functional parameter called key which can be a function and it'll pass each element of the list into that function and will sort the list based on what is returned by that key function. To sort a list of strings acc. to their length, myList.sort(key= len) Similarly key can be any other function as well.
30th Mar 2019, 12:45 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 6
ANU Glad that it's cleared now. If you find the answer for your question then consider marking it best with that green tick under the downvote to help other find it easily. And you can also tag people by using @ before the name. Type @ followed by first letter of the name and you'll see some name suggestions to tag.
30th Mar 2019, 1:13 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 5
Thank you "M. Watney" . I have this doubt from long time but now it is cleared.Thank u again.
30th Mar 2019, 1:11 PM
ANU
ANU - avatar