sort() method to sort a list

sort(reverse,key) takes two optional arguments .

reverse : True or False , by default reverse=False
key : the function to use for sorting

Returns None ( only sort the list without returning ).
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() # by default ascending 
print(my_list)
Output is here
[1, 2, 4, 7]
reverse=True
my_list=[4,2,7,1]
my_list.sort(reverse=True) # Descending  order
print(my_list) # Output  [7, 4, 2, 1]

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']

Return None

Here output is None
my_list=[4,2,7,1]
my_list=my_list.sort()
print(my_list) # None
All list methods Questions with solutions on List
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer