Python 101: How to Sort a List in 3 Easy Steps

Do The Thing
1 min readJan 10, 2023

--

Introduction

Sorting lists is a common task in programming, and Python makes it easy with its built-in sort() method. In this tutorial, we'll walk you through the steps of sorting a list in Python, using a simple example list of numbers.

Step 1: Create a List

First, let’s create a list of numbers that we want to sort. You can use any list of items that you want to sort, but for this example, we’ll use a list of integers.

numbers = [3, 1, 4, 2]

Step 2: Use the sort() Method

Now that we have our list, we can use the sort() method to sort the list in ascending order. The sort() method modifies the list in place, so you don't need to assign the sorted list to a new variable.

numbers.sort()

After running this code, our list numbers will be sorted in ascending order: [1, 2, 3, 4].

Step 3: (Optional) Sort in Descending Order

If you want to sort the list in descending order, you can use the sort() method with the reverse parameter set to True.

numbers.sort(reverse=True)

Now our list numbers is sorted in descending order: [4, 3, 2, 1].

Conclusion

Sorting a list in Python is easy with the built-in sort() method. Whether you want to sort a list of numbers in ascending or descending order, the sort() method has you covered. Happy coding!

--

--

Do The Thing
Do The Thing

No responses yet