0

What is the purpose of key=None, how to use key ? What can we place in place of None ?

I know that we can sort alphabetically/numerically in ascending or descending order by putting reverse = True or False list.sort(key=None, reverse=False)

4th Jun 2021, 5:02 AM
lisa
8 Réponses
+ 7
Here are a couple. You can use key= in both sorts, i.e. lst.sort(key=) and sorted(lst, key=) https://code.sololearn.com/cwB76GNUFftP The sort method sorts the list in place. The sorted function returns a sorted copy of the list. lst1 = [1, 3, 2] lst1.sort() print(lst1) # output [1, 2, 3] lst1 = [1, 3, 2] print(sorted(lst1)) # output [1, 2, 3]
4th Jun 2021, 5:32 AM
David Ashton
David Ashton - avatar
+ 3
l = ["first", "second", "third", "fourth", "fifth"] l.sort(key=len) # sort by length print(l)
4th Jun 2021, 5:35 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
At the bottom of the sort() doc there was a link that would have taken you to the "How To" area that would have described it further with examples. Here's that link. https://docs.python.org/3/howto/sorting.html#sortinghowto
4th Jun 2021, 5:52 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Here's a more detailed explanation https://code.sololearn.com/cHAqka9YOVph
5th Jun 2021, 8:18 PM
David Ashton
David Ashton - avatar
+ 1
Read the section for list.sort() in the docs. It describes what the key is for and reverse is kinda obvious, but it is also described. https://docs.python.org/3/library/stdtypes.html#list.sort
4th Jun 2021, 5:13 AM
ChaoticDawg
ChaoticDawg - avatar
0
assuming you are talking of function signature: if no values provided for 'key' and 'reverse' argument, default to 'None' (alphabetical sort) and 'False' (ascending order) key is used to provide a sort function wich overide the default one...
4th Jun 2021, 5:13 AM
visph
visph - avatar
0
ChaoticDawg there is no example provided in library/stdtypes, please provide me some example.
4th Jun 2021, 5:28 AM
lisa
- 1
Привет здесь есть русские
5th Jun 2021, 5:31 PM
makster
makster - avatar