« All list methods
sort(reverse,key) takes two optional arguments .
reverse
: True or False , by default reverse=False
key
: the function to use for sorting
Returns a copy of the sorted list .
my_list=['Ronald','John','Alex','Ravi']
my_list.sort()
print(my_list)
Output
['Alex', 'John', 'Ravi', 'Ronald']
my_list=[4,2,7,1]
my_list.sort()
print(my_list)
Output is here
[1, 2, 4, 7]
Using key
Length of the string is used for sorting.
my_list=['ab','xa','dc','Cxx','yzza','Z','b']
my_list.sort(key=len)
print(my_list)
Output
['Z', 'b', 'ab', 'xa', 'dc', 'Cxx', 'yzza']
Using reverse
Length of the string in reverse order is used ( maximum to minimum )
my_list=['ab','xa','dc','Cxx','yzza','Z','b']
my_list.sort(key=len,reverse=True)
print(my_list)
Output
['yzza', 'Cxx', 'ab', 'xa', 'dc', 'Z', 'b']
« All list methods « Questions with solutions on List