To sort a list in Python, you can use the sorted()
function or the sort()
method for ascending order. For descending order, you can use the sorted()
function with the reverse
parameter set to True
or the sort()
method with the reverse
parameter.
In this example,
numbers
with integer values.sorted()
function to sort the list in ascending order and store the sorted list in the variable sorted_numbers
.sorted()
function sorts the elements in natural order.numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(f"Sorted list in ascending order: {sorted_numbers}")
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
numbers
with integer values.sorted()
function with the reverse
parameter set to True
to sort the list in descending order and store the sorted list in the variable sorted_numbers
.sorted()
function with reverse=True
sorts the elements in reverse natural order.numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers, reverse=True)
print(f"Sorted list in descending order: {sorted_numbers}")
Sorted list in descending order: [8, 5, 3, 2, 1]
In this example,
numbers
with integer values.sort()
method to sort the list in ascending order.sort()
method sorts the elements in natural order.numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(f"Sorted list in ascending order: {numbers}")
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
numbers
with integer values.sort()
method with the reverse
parameter set to True
to sort the list in descending order.sort()
method with reverse=True
sorts the elements in reverse natural order.numbers = [5, 2, 8, 1, 3]
numbers.sort(reverse=True)
print(f"Sorted list in descending order: {numbers}")
Sorted list in descending order: [8, 5, 3, 2, 1]
In this tutorial, we learned How to Sort a List in Python language with well detailed examples.