Python list is used to store multiple elements in a single variable. These items can be in different types like string, integer, etc. Sometimes we may want to sort them accordingly. We can sort them in ascending or descending ways by using the sort()
provided by the list type.
Order String List Ascending
By default, the sort() method sorts provided elements in ascending order. If we provide a list that contains strings they are sorted alphabetically.
cities = ["London","Berlin","Newyork","Istanbul"]
cities.sort()
print(cities)
['Berlin', 'Istanbul', 'London', 'Newyork']
Order Integer(Number) List Ascending
The sort() method can be also used to sort a list of numbers or integers in ascending. The default behavior of the sort() method is ascending order.
numbers = [3,7,5,8,5,1]
numbers.sort()
print(numbers)
[1, 3, 5, 5, 7, 8]
Order String List Descending
The sort() method can be also used to sort a list of strings in descending order. The reverse
parameter is provided to the sort() method with the True
value. This sort is also called as reverse sort
.
cities = ["London","Berlin","Newyork","Istanbul"]
cities.sort(reverse=True)
print(cities)
['Newyork', 'London', 'Istanbul', 'Berlin']
Order Integer(Number) List Descending
The sort() method can be also used to sort a list of numbers or integers in descending order. The reverse
parameter is provided to the sort() method with the True
value. This sort is also called as reverse sort
.
numbers = [3,7,5,8,5,1]
numbers.sort(reverse=True)
print(numbers)
[8, 7, 5, 5, 3, 1]