sort() method to sort a list

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


plus2net.com



Post your comments , suggestion , error , requirements etc here





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