How to Sort Arrays and Lists in Python

When you work with Python, sooner or later you need to sort data – student marks, product prices, log records, or even custom objects like cities or employees. Recently, I had to remove duplicate elements from an array and realized that sorting the data first made the solution much simpler and faster.

In this tutorial, I’ll show you practical ways to sort arrays and lists in Python using sort() and sorted(), how to customize the sort order with the key and reverse parameters, and how to handle more advanced scenarios like custom objects and multiple criteria. You’ll also see real-world mistakes students make and simple exercises so you can practice along the way.

What Do We Mean by “Array” in Python?

In many beginner tutorials, including this one, the word “array” is used loosely to mean “a collection of values,” but in Python, there are a few different options:

  • Lists: The most commonly used built-in sequence type; very flexible and what we’ll focus on in this article.
  • array module: Provides compact numeric arrays; used less frequently in everyday scripting.
  • NumPy arrays: From the external NumPy library; widely used in data science and scientific computing.

In this tutorial, when we say “array,” we’ll primarily use Python lists because they are what most beginners and intermediate developers use in real projects.
The concepts you learn here also apply to other array types, like those from the array module or NumPy, as long as they support similar sorting operations.

Overview of Sorting in Python

Python gives you two primary tools for sorting:

  • list.sort() – a method that sorts a list in place (modifies the original list).
  • sorted(iterable) – a function that returns a new sorted list, leaving the original iterable unchanged.

Both support powerful options:

  • key – a function that computes a sort key for each item.
  • reverse – a boolean flag to reverse the final order.

Throughout this tutorial, you’ll see where each is appropriate and how to avoid common bugs.

Sort Lists with sort() and sorted()

In this section, we’ll start with basic examples using Python’s built-in sorting tools.

Use the sort() Method (In-place Sorting)

The sort() method is called on a list and sorts the list in place, meaning the original list itself is reordered.

Example: Sort a List of City Names

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

cities.sort()
print(cities)

Output:

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

You can refer to the screenshot below to see the output.

How to Sort Arrays and Lists in Python

Here cities.sort() reorders the existing list of city names alphabetically. Use sort() when you do not need to preserve the original order of the list, for example, when preparing data for display.

Example: Sort a List of Numbers

numbers = [34, 1, 23, 67, 2]

numbers.sort()
print(numbers)

Output:

[1, 2, 23, 34, 67]

The list of numbers is sorted in ascending order. Again, the numbers itself is modified; there is no new list created.

Common Mistake: Assigning the Result of sort()

A bug I often see in beginner code:

cities = ["New York", "Los Angeles", "Chicago"]
sorted_cities = cities.sort() # BUG: sorted_cities will be None

print(sorted_cities) # Prints: None
print(cities) # Prints the sorted list

The sort() method does not return the sorted list; it returns None. If you need a new list, use sorted() instead, as shown next.

Use the sorted() Function (Returns New List)

The sorted() function takes any iterable (list, tuple, string, etc.) and returns a new sorted list, leaving the original data unchanged.

Example: Sort a List of City Names

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']

You can refer to the screenshot below to see the output.

Sort Arrays and Lists in Python

sorted_cities is a new sorted list, while cities remains in its original order. Use sorted() when you want multiple views of the same data (for example, sorted and unsorted) or when you’re working with immutables like tuples.

Custom Sorting in Python Using the key Parameter

In real projects, you rarely sort just by the default order.
You might need to sort by:

  • Length of a string
  • A specific character
  • A field inside a dictionary
  • A property of an object

Both sort() and sorted() have a key parameter that lets you define how items should be compared.

Example: Sort City Names by String Length

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

cities.sort(key=len)
print(cities)

Output:

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

Here key=len tells Python to compute the length of each city name and sort based on that length.
This pattern works with any function that takes one item and returns a value to sort by.

Try it yourself:

  • Change key=len to key=lambda city: city.count(“o”) to sort by the number of the letter "o" in each city name.
  • Observe how the order changes.

Example: Sort City Names by Last Character

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

sorted_cities = sorted(cities, key=lambda city: city[-1])
print(sorted_cities)

Output:

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

You can refer to the screenshot below to see the output.

Sort Arrays and Lists Python

Here the key function returns the last character of each city name (city[-1]).
Python sorts based on those last characters.

Example: Sort a List of Dictionaries by a Field

Let’s move to a more realistic example: sorting employees by salary.

employees = [
{"name": "Alice", "salary": 95000},
{"name": "Bob", "salary": 75000},
{"name": "Charlie", "salary": 120000},
]

employees.sort(key=lambda e: e["salary"])
print(employees)

Output:

[
{'name': 'Bob', 'salary': 75000},
{'name': 'Alice', 'salary': 95000},
{'name': 'Charlie', 'salary': 120000}
]

The key function returns e[“salary”] for each employee, so the list is sorted by salary in ascending order.
This approach is much cleaner than writing a custom sorting algorithm or nested loops.

Try it yourself:

  • Add a “department” key and sort by department name instead of salary.
  • Then sort by salary in descending order using reverse=True (shown in the next section).

Sort in Reverse Order (Descending)

Sometimes you need to sort from largest to smallest – for example, top scores, highest salary, or latest date first.
Both sort() and sorted() support a reverse parameter.

Example: Sort Numbers in Descending Order

numbers = [34, 1, 23, 67, 2]

numbers.sort(reverse=True)
print(numbers)

Output:

[67, 34, 23, 2, 1]

Setting reverse=True simply reverses the final ordering result.
Internally, Python still uses the same efficient sorting algorithm; you do not need to implement your own descending sort logic.

Example: Sort City Names 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']

This sorts the city names in reverse alphabetical order.

Try it yourself:

  • Take the employees’ list from the previous section and sort it by salary in descending order using key and reverse=True.

Advanced Sorting in Python: Custom Objects and Multiple Criteria

In real-world applications, you often work with custom classes or need to sort by more than one criterion.
Python’s sorting remains powerful and readable even in these cases.

Example: Sort Custom Objects

Imagine a City class with name and population attributes.

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)]

We pass key=lambda city: city.population to sort the City objects by population.
Depending on your application, you could also sort by city.name or any other attribute.

Real-world tip:
Choosing the “natural” sorting attribute for a class is important.
For cities, population or name might be appropriate; for Employee, it might be name, employee ID, or hire date.

Example: Sort by Multiple Criteria

You can sort by multiple keys by returning a tuple from the key function.
Python compares tuples lexicographically (first element, then second, etc.).

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)]

You can refer to the screenshot below to see the output.

How to Sort Arrays and Lists Python

Here:

  • city[1] is the population
  • city[0] is the city name

So we sort by population first, and for cities with the same population, we fall back to sorting by name.

Try it yourself:

  • Create a list of (student_name, marks, age) tuples.
  • Sort first by marks (descending), then by age (ascending), then by name.

How Fast Is Python’s Sort? (And Is It Stable?)

Python’s built-in sort() and sorted() use an algorithm called Timsort:

  • Time complexity is generally O(nlog⁡n)O(nlogn).
  • It is optimized for partially sorted data, which is common in real workloads.

Python’s sort is also stable, meaning:

  • If two items compare as equal according to the key, their original order is preserved.
  • This is why sorting by multiple criteria works smoothly: you can sort by one criterion and then another without losing the previous order.

For large lists, this built-in sort is almost always the right choice instead of trying to write your own algorithm.

Common Sorting Mistakes and How to Avoid Them

From teaching beginners and working on projects, these are mistakes I see frequently:

  • Expecting sort() to return a new list
    • Fix: Remember sort() sorts in place and returns None. Use sorted() to get a new list.
  • Forgetting to use key and manually implementing complex comparison logic
    • Fix: Use key functions for derived values like string length, lowercased versions, or object attributes.
  • Sorting strings that represent numbers without converting them
    • Example: [“10”, “2”, “3”] sorted lexicographically becomes [“10”, “2”, “3”].
    • Fix: Convert to integers first: sorted(int(x) for x in list_of_strings).
  • Overcomplicating descending order

Real-world Mini Case Study

In one of my projects, I had to analyze a large log file and sort entries by timestamp and then by severity level (ERRORWARNINGINFO).
Instead of writing a custom algorithm, I used a combination of key and tuple sorting:

logs = [
# Imagine this list contains objects or tuples with timestamp and severity
# Example tuple: (timestamp, severity, message)
]

# Assuming each log is a tuple: (timestamp, severity, message)
logs_sorted = sorted(logs, key=lambda log: (log[0], log[1]))

This kept the code short, readable, and easy to maintain. Whenever you feel tempted to write nested loops to sort, think about whether a simple key function could replace all that logic.

Practice Exercises

Here are a few exercises to help you strengthen your understanding:

  1. Student Marks
    • Create a list of dictionaries: {“name”: “StudentName”, “marks”: number}.
    • Sort by marks ascending, then by name.
  2. Product Catalog
    • Create a list of (product_name, price, rating) tuples.
    • Sort by rating (descending), then by price (ascending).
  3. Custom Class
    • Create an Employee class with namesalary, and hire_date.
    • Sort a list of employees by hire date, then by salary.

Try implementing each using both sort() and sorted() where appropriate.

Conclusion

In this tutorial, you learned how to sort arrays and lists in Python using the built-in sort() method and sorted() function, and when to choose each one. You explored custom sorting with the key parameter, reverse sorting with reverse=True, and advanced scenarios like sorting custom objects and multiple criteria.

With these patterns and examples, you can write cleaner, more readable sorting logic in your Python projects and avoid common mistakes that many beginners make.

You may read:

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.