How to sort a list in python?
The sort() function sorts the items of the list, by default in increasing order. This is done “in place”, i.e., it does not create a new list.
It is used in the following syntax:-
list.sort()
e.g.,
t1=['1', '4', '2', '6'] t1.sort() print(t1)
output- ['1', '2', '4','6']
Like reverse(), sort() also performs its function and does not return anything.
To sort a list in decreasing order using sort(), we can use:-
list.sort(reverse=True)
t1=['1', '4', '2', '6'] t1.sort(reverse=True) print(t1)
output=['6', '4', '2', '1']
Sort() has two parameters:-
- reverse- If True, list is sorted in descending order.
- key-function that serves as a key for the sort comparison.
t1=['python', 'blog', 'pythonpoint', 'Cpython'] t1.sort(key=len) print(t1)
output-['blog', 'python', 'Cpython', 'pythonpoint']
This is all about sorting a list.
Subscribe
Login
Please login to comment
0 Discussion