Understanding the Different Ways of Sorting a List in Python

As a world-class Python developer, I often encounter situations where the built-in sort() function of lists isn’t suitable or efficient. In this article, we’ll explore various methods to sort a list …

Updated November 23, 2023

As a world-class Python developer, I often encounter situations where the built-in “sort()” function of lists isn’t suitable or efficient. In this article, we’ll explore various methods to sort a list without using the sort() function.

  1. Using Built-In Sort Functions: The simplest method for sorting in Python is by using built-in functions such as sorted(). This function does not modify the original list but returns a new, sorted list. If you want to sort the original list, you can use the sorted() function with “list = list” assignment.
unsorted_list = [34, 5, 27, 89]
sorted_list = sorted(unsorted_list)

or

unsorted_list = [34, 5, 27, 89]
unsorted_list.sort()
  1. Using the List Comprehension: This method is a bit advanced and only works if you need to create a new sorted list from an existing one. Here’s how it can be done:
unsorted_list = [34, 5, 27, 89]
sorted_list = [i for i in unsorted_list if i < 30]

The sorted list is created using the new list comprehension syntax. It checks each number in the original list and only adds it to the new list if the condition (i < 30) is met. 3. Using Sort() Method: You can also use sort method to sort a list without changing its length but remember that, sorting methods like sort(), reverse() or sorted() changes the original list in-place.

unsorted_list = [34, 5, 27, 89]
unsorted_list.sort()
  1. Using sorted() Function on a List: You can also use sorted function to create a new sorted list from an existing one and the original list remains unchanged. This method is used when you need to sort multiple lists simultaneously or if there are complex conditions for sorting.
unsorted_list1 = [34, 5, 27, 89]
unsorted_list2 = sorted(unsorted_list1)

In the above example, unsorted_list2 is a new list and unsorted_list1 remains unchanged. The sorted function doesn’t modify the original list but returns a new one.

Remember that sorting methods don’t always return a list in the order you might expect. For example, with lists of mixed types, like [34, ‘dog’, 27], the sort method will place these elements in an arbitrary order, not numerical order.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!