How To Sort A List In Ascending Order In Python

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:

  • 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:

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:

  • 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:

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:

Output:

['apple', 'banana', 'kiwi', 'mango']

Example using sort() method:

Output:

['apple', 'banana', 'kiwi', 'mango']

Full code

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.