How to sort list in Python
![how to sort list in python](https://pythonpoint.net/wp-content/uploads/2020/11/How-to-sort-list-in-Python-1024x576.jpg)
The sort() function can be used to sort the list. You can sort it in the ascending order, descending order or even in user defined order.
Syntax:
list_name.sort(reverse=True/False, key=fucntion_name)
- reverse – optional parameter. reverse=True will sort in descending order. Default value of reverse is False.
- key – optional parameter. a function to specify the sorting criteria
Example 1:
names = ['Chris', 'Navneet', 'Abu', 'Malu' ] names.sort() print(names)
Output:
['Abu', 'Chris', 'Malu', 'Navneet']
Example 2:
names = ['Chris', 'Navneet', 'Abu', 'Malu' ] names.sort(reverse=True) print(names)
Output:
['Navneet', 'Malu', 'Chris', 'Abu']
Example 3:
def leng(e): return len(e) names = ['Chris', 'Navneet', 'Abu', 'Malu' ] names.sort(key=leng) print(names)
Output:
['Abu', 'Malu', 'Chris', 'Navneet']
Subscribe
Login
Please login to comment
0 Discussion