Python list sort()
The sort function can be used to sort a list in ascending, descending or user defined order.
Sorting list of integer in python
Example 1:
sorting list of integer in ascending order.
list_of_numbers = [10, 30, 44, 22]
# Sorting list of Integers in ascending
list_of_numbers.sort()
print(list_of_numbers)
Output:
[10, 22, 30, 44]
sorting list of integer in descending order.
list_of_numbers = [10, 30, 44, 22]
# Sorting list of Integers in ascending
list_of_numbers.sort(reverse=True)
print(list_of_numbers)
Output:
[44, 30, 22, 10]
Example 2:
Sort the list of string/words alphabetically in python
Sort the list in ascending order
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output: ['BMW', 'Ford', 'Volvo']
Sort the list descending order
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
Output: ['Volvo', 'Ford', 'BMW']
Sort the list of words by the length of the word:
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=lambda word: len(word))
print(cars)
Output: ['VW', 'BMW', 'Ford', 'Mitsubishi']
Example 3:
Sort a list of dictionaries based on the "year" value of the dictionaries:
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=lambda element: element['year'])
print(cars)
Output:
[{'car': 'Mitsubishi', 'year': 2000}, {'car': 'Ford', 'year': 2005}, {'car': 'VW', 'year': 2011}, {'car': 'BMW', 'year': 2019}]