To sort a list in ascending order in Python, you can use the sort()
method or the sorted()
function.
In this example,
numbers
with integer values.sort()
method on the numbers
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.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,
words
with string values.sort()
method on the words
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.words = ["banana", "apple", "cherry"]
words.sort()
print(f"Sorted list in ascending order: {words}")
Sorted list in ascending order: ['apple', 'banana', 'cherry']
In this tutorial, we learned How to Sort a List in Ascending Order in Python language with well detailed examples.