In this tutorial, we will learn how to sort a list in ascending order in Python. Sorting is a common operation in programming and is often used to arrange data in a meaningful way. In Python, we can use built-in functions and methods to sort a list easily.
Step 1: Understanding the “sorted()” function
Python has a built-in function sorted() that can be used to sort items in an iterable such as a list, tuple, or string. The function takes an iterable as input and returns a new sorted list from the elements of the given iterable.
The basic syntax of the sorted() function is:
1 |
sorted(iterable, key=None, reverse=False) |
- iterable: The items to be sorted.
- key (optional): A custom function that serves as a key to determine the ordering of elements.
- reverse (optional): If set to True, the list is sorted in descending order.
Let’s see an example:
1 2 3 4 |
numbers = [34, 12, 67, 89, 6] sorted_numbers = sorted(numbers) print(sorted_numbers) |
Output:
[6, 12, 34, 67, 89]
Step 2: Sorting a list using the list method “sort()”
Another way to sort a list is to use the sort() method of a list object. The sort() method modifies the list in-place and returns None.
The syntax of the sort() method is:
1 |
list_name.sort(key=None, reverse=False) |
- key (optional): A custom function that serves as a key to determine the ordering of elements.
- reverse (optional): If set to True, the list is sorted in descending order.
Let’s sort the list numbers in ascending order:
1 2 3 4 |
numbers = [34, 12, 67, 89, 6] numbers.sort() print(numbers) |
Output:
[6, 12, 34, 67, 89]
Step 3: Sorting a list of strings
You can also sort a list of strings using both the sorted() function and the sort() method. By default, strings are sorted in alphabetical order.
Example using sorted() function:
1 2 3 4 |
fruits = ['apple', 'banana', 'kiwi', 'mango'] sorted_fruits = sorted(fruits) print(sorted_fruits) |
Output:
['apple', 'banana', 'kiwi', 'mango']
Example using sort() method:
1 2 3 4 |
fruits = ['apple', 'banana', 'kiwi', 'mango'] fruits.sort() print(fruits) |
Output:
['apple', 'banana', 'kiwi', 'mango']
Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
numbers = [34, 12, 67, 89, 6] sorted_numbers = sorted(numbers) print(sorted_numbers) numbers.sort() print(numbers) fruits = ['apple', 'banana', 'kiwi', 'mango'] sorted_fruits = sorted(fruits) print(sorted_fruits) fruits.sort() print(fruits) |
Conclusion
In this tutorial, we learned about two ways to sort a list in ascending order in Python using the sorted() function and the sort() method. Sorting lists is crucial in numerous applications and Python provides easy-to-use built-in functions and methods for this purpose.