About Python List Sorting
In Python, list maintains the order of the elements as they are inserted or created.
So, list elements can be sorted in ascending or descending order.
Sorting Python list elements in ascending order
Using sort() Method:
1. Create a list of string with fruit names (fruit_list = ["Banana", "Apple", "Orange", "Cherry"]
) where fruit_list
is the list variable and ["Banana", "Apple", "Orange", "Cherry"]
is the list with elements. The list elements are not in ascending order.
2. To sort the elements of the above list, you can use fruit_list.sort()
where sort()
method is used to sort the list elements in ascending order. If you now print the fruit_list, the list elements will be printed in ascending order.
In the second example, a list of integer numbers has been sorted in ascending order.
Please take a closer look at the following examples:
Example of sorting list elements using sort() method
Output of the above example
Sorted list of string elements: ['Apple', 'Banana', 'Cherry', 'Orange'] Sorted list of integer elements: [1, 2, 3, 4, 5]
Using sorted() function:
1. Create a list of string with fruit names (fruit_list = ["Banana", "Apple", "Orange", "Cherry"]
) where fruit_list
is the list variable and ["Banana", "Apple", "Orange", "Cherry"]
is the list with elements. The list elements are not in ascending order.
2. Use sorted_list = sorted(fruit_list)
where sorted_list
is a variable and sorted(fruit_list)
is the sorted() function with list argument. If you now print the sorted_list, the list elements will be printed in ascending order.
In the second example, a list of integer numbers has been sorted in ascending order.
Please take a closer look at the following examples:
Example of sorting list elements using sorted() function
Output of the above example
Sorted list of string elements: ['Apple', 'Banana', 'Cherry', 'Orange'] Sorted list of integer elements: [1, 2, 3, 4, 5]