PYTHON

Python List sort() Method: Syntax, Usage, and Examples

The Python sort() method organizes the elements of a list in ascending or descending order. As an in-place sorting method, sort() modifies the original list without creating a new list.

How to Use sort() in Python Lists

As a list method, insert() needs a list to insert the element into and takes an optional reverse parameter that can be True or False.

Without an additional parameter, sort() organizes elements in ascending order by default. Here's the basic syntax of using the sort() method:

# Creating a list of numbers and sorting them
numbers = [5, 2, 9, 1]
numbers.sort()  # Sorts the numbers in ascending order
print(numbers)  # Outputs: [1, 2, 5, 9]

You can sort the list in descending order by passing reverse=True as an argument:

numbers.sort(reverse=True)
print(numbers)  # Outputs: [9, 5, 2, 1]

When to Use sort() in Python Lists

Organizing Data

In Python, sorting lists is essential when you need to organize or order data. This can simplify further operations like searching or data processing.

scores = [88, 94, 72, 91, 85]
scores.sort()
print(scores)  # Outputs the sorted list of scores

Preparing for Output

Before generating reports or output, sorting data can help present it in a more readable format.

names = ["Alice", "Bob", "Charlie"]
names.sort()
print("Registered participants: ", names)

Enhancing User Experience

Displaying sorted lists can also help users better navigate or understand content.

products = ["apple", "banana", "cherry"]
products.sort()
print("Available products:", products)

Examples of Using sort() in Python Lists

E-commerce Product Listings

For e-commerce platforms, sort() can manage the display order of products based on price, name, or other attributes.

product_prices = [('T-shirt', 20), ('Jeans', 45), ('Socks', 5)]
product_prices.sort(key=lambda item: item[1])  # Sorts by price
print("Products sorted by price:", product_prices)

Academic Grading Systems

In academic or educational applications, sorting can rank students based on their grades or scores.

grades = [("Student A", 88), ("Student B", 92), ("Student C", 85)]
grades.sort(key=lambda x: x[1], reverse=True)  # Sorts by score descending
print("Student rankings:", grades)

Sorting Custom Objects

When working with lists of custom objects, you can sort these lists by attributes using a key function.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

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

products = [Product("Apple", 1.2), Product("Banana", 0.5), Product("Cherry", 0.8)]
products.sort(key=lambda product: product.price)
print(products)

Learn More About the Python List sort() Method

Using sort() with the key Parameter

The key parameter of the sort() method allows you to change the sorting behavior based on specific criteria. key needs to reference a function that returns a value for sorting. This is especially useful for sorting the list based on criteria like an element's length.

# Sorting based on length of the string
strings = ["banana", "apple", "cherry"]
strings.sort(key=len)
print(strings)  # Outputs: ['apple', 'banana', 'cherry']

Sort vs. sorted()

While sort() modifies the list in place, Python also offers a sorted() function that creates a new sorted list from the elements of any iterable.

The sort() method modifies a list in place. However, there's a built-in function that creates and returns a sorted list instead. Using sorted(), a special sort function in Python, the original list remains the same.

original = [5, 2, 9, 1]
sorted_list = sorted(original)
print("Original:", original)
print("Sorted:", sorted_list)

Sorting Complex Structures

The sort() method in Python also works with more complex structures such as lists of dictionaries, tuples, and even nested lists. The key parameter is particularly helpful in these cases. key even allows you to define the sorting criteria based on specific elements as a lambda function.

# Sorting a list of lists
list_of_lists = [[3, 4], [1, 2], [5, 6]]
list_of_lists.sort(key=lambda x: x[0])
print("Sorted list of lists:", list_of_lists)

Performance Implications of sort()

Typically using Timsort, the sort() method is highly efficient. However, for large lists, the impact on performance can be significant. In particular, you might encounter performance issues when you sort frequently within a loop or a highly interactive application. In such cases, you might need to optimize your approach as best as possible.

# Frequent sorting within a loop
large_list = [random.randint(1, 1000) for _ in range(10000)]
for _ in range(100):
    large_list.sort()  # Repeated sorting

sort(reverse=True) vs. reverse()

While sort(reverse=True) sorts a list in descending order, using the reverse() method after sort() is another way to get the same result. reverse() can reverse the elements of a list after sorting in ascending order. This might be preferable when the sorting criterion changes dynamically.

# Sorting then reversing
numbers = [5, 2, 9, 1]
numbers.sort()
numbers.reverse()
print(numbers)  # Outputs: [9, 5, 2, 1]

Cultural Considerations in Sorting

Sorting operations may need to consider locale-specific rules, especially when dealing with localized applications. For a localized list, Python's sort() has no built-in localization setting. But you can use the locale module to change how string sorting behaves.

import locale
locale.setlocale(locale.LC_COLLATE, 'de_DE.UTF-8')

names = ["Äpfel", "Bananen", "Kirschen"]
names.sort(key=locale.strxfrm)
print(names)
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH