sort() method in Python Lists can be used to sort all the elements of a Python List in the ascending order.
The sort() method in Python Lists returns ‘None‘ as a value, however, it modifies the original array.
Syntax
list.sort()
l = [3, 1, 5, 2, 6]
print(l.sort()) # returns None
print(l) # returns sorted list
O/P
None
[1, 2, 3, 5, 6]
If we want to sort the elements of the list into descending order, then we can write ‘reverse=True‘ in the sort method as :
l = [3, 1, 5, 2, 6]
l.sort(reverse = True) # returns None
print(l) # returns sorted list
O/P
[6, 5, 3, 2, 1]
If you don’t want to use sort() method to sort Python list, then, you can do it using any of the pre-defined sorting techniques like bubble sort, selection sort, insertion sort, merge sort, quick sort etc.
We can also use sorted() method to sort the Python List.
The sorted() function returns a sorted list of the specified iterable object.
You can specify ascending or descending order.
l = [3, 1, 5, 2, 6]
print(sorted(l)) # returns sorted list
print(sorted(l, reverse=True)) # returns sorted list
O/P
[1, 2, 3, 5, 6]
[6, 5, 3, 2, 1]
That’s all here.
