How to Sort an Array in Python?

A few weeks ago, I was working on a Python project where I had a requirement to remove duplicate elements from an array. The sorting technique helped me to do that. So, in this article, I will explain all the ways to sort an array in Python with some real examples.

Sort an Array in Python using Built-in Sorting Methods

There are two primary ways to sort arrays in Python. They are the sort() method and the sorted() method, and each of them has its functionality.

Using the sort() Method

The sort() method in Python sorts the list, but it modifies the original list. We use this method when we do not want to keep the original list.

Example: Sorting a List of City Names.

Let us consider an example of a list of city names in the USA:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
cities.sort()
print(cities)

Output:

['Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']

I have executed the example code and added the screenshot below for reference.

Sort an Array in Python using sort()

This example shows the sort() method in Python sorts the list alphabetically.

Check out How to Update an Array in Python.

Example: Sorting a List of Numbers.

Let us consider an example of a list of numeric values:

numbers = [34, 1, 23, 67, 2]
numbers.sort()
print(numbers)

Output:

[1, 2, 23, 34, 67]

Refer to the screenshot of the executed code below.

Sort an Array of numbers in Python using sort()

This example shows the sort() method in Python sorts the list of numeric values in order.

Using the sorted() Function

The sorted() method in Python returns a new list, which does not affect the original list. We use this method when we want to keep the original list.

Example: Sorting a List of City Names.

Let us consider some cities in the USA and apply the sorted() method:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
sorted_cities = sorted(cities)
print(sorted_cities)
print(cities)

Output:

['Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']
['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']

I have added a screenshot of the executed example code here.

Sort an Array in Python using sorted()

In the above example, sorted_cities contains a sorted list of that cities is left unchanged.

Read How to Print Duplicate Elements in Array in Python.

Array Custom Sorting with Key Functions in Python

We may get some scenarios where we need to custom sort arrays in Python. Both sort() and sorted() methods accept the key parameters and allow custom sorting.

Example: Sorting by String Length.

Let us know if you want to sort the list of cities names by their length:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
cities.sort(key=len)
print(cities)

Output:

['Chicago', 'Houston', 'Phoenix', 'New York', 'Los Angeles']

I have executed the example code and added the screenshot below for reference.

Sort an Array in Python using sort() by String Length

Example: Sorting by Last Character.

To sort the list of city names by their last character:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
sorted_cities = sorted(cities, key=lambda city: city[-1])
print(sorted_cities)

Output:

['Phoenix', 'Chicago', 'Los Angeles', 'Houston', 'New York']

Sort Python Array in Reverse Order

In Python, both the sort()and sorted() methods have a reverse parameter, which allows you to sort lists in descending order.

Example: Sorting Numbers in Descending Order.

Let us consider the below example to sort a list in descending order:

numbers = [34, 1, 23, 67, 2]
numbers.sort(reverse=True)
print(numbers)

Output:

[67, 34, 23, 2, 1]

Example: Sorting City Names in Reverse Alphabetical Order.

City names are sorted in reverse alphabetical order:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
sorted_cities = sorted(cities, reverse=True)
print(sorted_cities)

Output:

['Phoenix', 'New York', 'Los Angeles', 'Houston', 'Chicago']

Read Convert String To Byte Array Python

Advanced Array Sorting Techniques in Python

Complex sorting in Python needs advanced sorting techniques, which may be custom objects or using multiple criteria. The sorting capabilities of Python can be extended.

Example: Sorting Custom Objects.

Let us sort a list of City objects by population, by creating a City class:

class City:
    def __init__(self, name, population):
        self.name = name
        self.population = population

    def __repr__(self):
        return f"{self.name} ({self.population})"

cities = [
    City("New York", 8419000),
    City("Los Angeles", 3980000),
    City("Chicago", 2716000),
    City("Houston", 2328000),
    City("Phoenix", 1690000)
]

cities.sort(key=lambda city: city.population)
print(cities)

Output:

[Phoenix (1690000), Houston (2328000), Chicago (2716000), Los Angeles (3980000), New York (8419000)]

Example: Sorting by Multiple Criteria

Let us sort cities by population and name, by using multiple criteria and using a tuple as the key:

cities_population = [("New York", 8419000), ("Los Angeles", 3980000), ("Chicago", 2716000), ("Houston", 2328000), ("Phoenix", 1690000)]
cities_population.sort(key=lambda city: (city[1], city[0]))
print(cities_population)

Output:

[('Phoenix', 1690000), ('Houston', 2328000), ('Chicago', 2716000), ('Los Angeles', 3980000), ('New York', 8419000)]

Read How to Unpack a Tuple in Python.

Conclusion

In this article, I have explained various ways to sort an array in Python. We have covered sorting an array in Python using built-in sorting methods by using sort() and sorted() and array custom sorting with key functions. We also discussed sorting Python arrays in reverse order and advanced array sorting techniques in Python.

I hope this tutorial has helped you to understand how to sort an array in Python.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.