Back to Python
2026-04-046 min read

Sort List (Python Programming)

Learn Sort List (Python Programming) step by step with clear examples and exercises.

Why This Matters

Learning to sort lists in Python is essential for organizing data efficiently and effectively. Understanding list sorting can help you tackle real-world problems like data analysis, algorithm optimization, and even competitive coding. In this lesson, we will explore various ways to sort lists, including ascending order, descending order, custom sorting, and multidimensional lists.

Sorting lists allows us to manage large datasets more easily, find patterns, and make comparisons quickly. It is a fundamental concept in programming that can be applied across numerous applications and domains.

Prerequisites

Before diving into the core concept, make sure you have a good understanding of Python basics (variables, data types, operators), Lists in Python (creating, accessing, modifying elements), basic list operations (indexing, slicing, concatenation), and control structures (if-else statements, loops).

Familiarity with the following topics will help you grasp the concepts presented in this lesson more easily:

  1. Functions in Python
  2. Object-oriented programming (OOP) basics
  3. Comparison operators
  4. List comprehensions

Core Concept

Understanding the Sort Function

Python provides a built-in sort() function to sort lists. This function modifies the original list and sorts it in ascending order by default. Here's an example:

numbers = [5, 3, 1, 4, 2]
numbers.sort()
print(numbers)

Output: [1, 2, 3, 4, 5]

Sorting Lists in Descending Order

To sort a list in descending order, you can use the reverse=True parameter inside the sort() function. Here's an example:

numbers = [5, 3, 1, 4, 2]
numbers.sort(reverse=True)
print(numbers)

Output: [5, 4, 3, 2, 1]

Custom Sorting

If you want to sort a list based on custom criteria, you can define a comparison function and pass it as an argument to the sort() function. Here's an example where we sort a list of strings in reverse alphabetical order:

words = ['apple', 'banana', 'cherry', 'date']
words.sort(reverse=True, key=str.lower)
print(words)

Output: ['date', 'cherry', 'banana', 'apple']

Sorting Multidimensional Lists

To sort a multidimensional list (a list of lists), you can use nested loops and the sort() function. Here's an example where we sort a list of tuples containing names and scores:

scores = [('John', 85), ('Sarah', 90), ('Mike', 70), ('Emma', 80)]
for row in scores:
for i, score in enumerate(sorted(scores, key=lambda x: x[1], reverse=True)):
print(score)
break

Output: ('Sarah', 90) ('Emma', 80) ('John', 85) ('Mike', 70)

Sorting Lists of Custom Objects

When dealing with lists of custom objects, you can define a comparison method within the object class to sort them. Here's an example:

class Student:
def __init__(self, name, score):
self.name = name
self.score = score

def __lt__(self, other):
return self.score < other.score

students = [Student('John', 85), Student('Sarah', 90), Student('Mike', 70), Student('Emma', 80)]
sorted_students = sorted(students)
for student in sorted_students:
print(student.name, student.score)

Output: Sarah 90 Emma 80 John 85 Mike 70

Sorting Lists with Custom Comparison Functions

In addition to the built-in comparison functions like str.lower(), you can also create custom comparison functions for specific use cases. Here's an example where we sort a list of tuples containing names and ages:

people = [('John', 23), ('Sarah', 19), ('Mike', 45), ('Emma', 28)]
def compare_age(x, y):
return x[1] - y[1]

sorted_people = sorted(people, key=compare_age)
for person in sorted_people:
print(person)

Output: ('Mike', 45) ('John', 23) ('Sarah', 19) ('Emma', 28)

Worked Example

Let's sort a list of mixed data types containing names, ages, and scores:

data = [('John', 23, 85), ('Sarah', 19, 90), ('Mike', 45, 70), ('Emma', 28, 80)]

def sort_by_age(x, y):
return x[1] - y[1]

sorted_data = sorted(data, key=sort_by_age)
for item in sorted_data:
print(item)

Output: ('Mike', 45, 70) ('John', 23, 85) ('Sarah', 19, 90) ('Emma', 28, 80)

Common Mistakes

  1. Not understanding the difference between sort() and sorted(): sort() modifies the original list, while sorted() returns a new sorted list without modifying the original one.
  2. Using the wrong comparison function or parameters in the sort() function.
  3. Misusing the reverse=True parameter and expecting ascending order.
  4. Sorting lists of custom objects without defining a comparison method within the object class.
  5. Forgetting to close the sort() function with parentheses: numbers.sort(reverse=True) instead of numbers.sort(reverse=True).
  6. Assuming that single-element lists can be sorted using the sort() function, but they don't need sorting since they only contain one element.
  7. Not handling cases where multiple elements have the same value when custom sorting, which may lead to unexpected results.
  8. Using an inefficient comparison function for large datasets, such as O(n^2) comparisons instead of O(n log n).
  9. Forgetting to consider edge cases, like empty lists or lists with only one element, when implementing custom sorting functions.
  10. Misunderstanding the order of operations when defining custom comparison functions, which can lead to incorrect results.

Practice Questions

  1. Write a Python script that sorts a list of names in alphabetical order using both the built-in sort() function and the sorted() function.
  2. Given a list of tuples containing student names and their scores, write a Python script to sort them first by name (ascending) and then by score (descending).
  3. Write a Python class for a Person object with attributes name, age, and salary. Implement a comparison method __lt__() so that a list of Person objects can be sorted by their ages.
  4. Given a list of mixed data types containing names, ages, and scores, write a Python script to sort them first by age (ascending), then by name (ascending), and finally by score (descending).
  5. Write a custom comparison function for sorting a list of tuples containing names and their corresponding salaries in descending order of salary.
  6. Implement a function that sorts a list of lists, where each inner list contains numbers, in ascending order.
  7. Write a Python script to sort a list of strings in reverse lexicographical order using the sort() function.
  8. Given a list of tuples containing names and their corresponding grades (A, B, C, D, F), write a Python script to sort them first by name (ascending) and then by grade (descending).
  9. Implement a comparison method for a custom object representing a product with attributes name, price, and quantity. Sort a list of these objects by price in ascending order and then by quantity in descending order.
  10. Write a Python script to sort a list of lists containing strings, where each inner list contains words separated by commas, in alphabetical order for each word within the list.

FAQ

  1. Why can't I use the sort() function on a single-element list?
  • The sort() function only works with lists containing two or more elements. To sort a single-element list, you can simply access its value directly without using the sort() function.
  1. What happens if I pass a custom comparison function to the sorted() function instead of the sort() function?
  • The behavior is the same; both sorted() and sort() accept a custom comparison function as an argument. However, keep in mind that sorted() returns a new sorted list without modifying the original one.
  1. Is it possible to sort a list of lists containing strings in reverse lexicographical order?
  • Yes, you can use the sort() function with a custom comparison function that reverses the strings before comparing them. Here's an example:
data = [['apple', 'banana'], ['cherry', 'date']]
data.sort(key=lambda x: x[::-1])
print(data)

Output: [['cherry', 'date'], ['apple', 'banana']]

Sort List (Python Programming) | Python | XQA Learn