Sorting in Python with Sorted: 7 Powerful Tips

Sorting in Python with sorted function is one of the most powerful ways to organize data quickly. Whether you are working with numbers, strings, or complex objects, the sorted() function offers speed, flexibility, and clarity.

This guide explores how the sorted() function works, its key parameters, and best practices for real-world applications. By the end, you’ll know how to sort any data type with precision.

Why Use the Sorted Function in Python?

The sorted() function in Python is essential because it allows you to arrange elements from an iterable (like lists, tuples, sets, or strings) into a new sorted list. Importantly, it does not change the original data.

Sorting in Python with sorted function is valuable for tasks such as ranking scores, arranging names alphabetically, and ordering complex datasets. Its ability to handle both simple and advanced use cases makes it indispensable.

Basic Example: Sorting Numbers

Sorting numbers with sorted() is simple. You just pass a list of integers or floats, and Python returns a new sorted list.

points = [0, -10, 15, -2, 1, 12]
sorted_points = sorted(points)
print(sorted_points)  # [-10, -2, 0, 1, 12, 15]

Here, the function sorts numbers in ascending order by default. Negative values are handled correctly, and the original list remains unchanged.

Sorting Strings with Sorted

The sorted() function also works with strings, arranging them in lexicographic (alphabetical) order.

children = ["Sue", "Jerry", "Linda"]
sorted_children = sorted(children)
print(sorted_children)  # ['Jerry', 'Linda', 'Sue']

By default, Python sorts strings based on Unicode values, meaning uppercase and lowercase letters can affect the order. To sort case-insensitively, you can use a custom key.

Customizing Sorting with the Key Argument

One of the most powerful features of sorted() is the key argument. This allows you to specify a function that defines the sorting criteria.

students = [("Alice", "B", 12), ("Eliza", "A", 16), ("Tae", "C", 15)]
sorted_by_grade = sorted(students, key=lambda student: student[1])
print(sorted_by_grade)

In this example, the list of student tuples is sorted by their grade (the second element). The key argument makes it easy to sort by attributes or custom logic.

Sorting in Descending Order

By default, sorting is ascending. To reverse the order, simply use the reverse=True argument.

sorted_points_desc = sorted(points, reverse=True)
print(sorted_points_desc)  # [15, 12, 1, 0, -2, -10]

This is helpful for ranking systems, leaderboards, or when you need the largest values first.

Sorting Dictionaries by Keys or Values

Python dictionaries are unordered collections, but you can sort them by keys or values using the sorted() function.

leaderboard = {231: "CKL", 123: "ABC", 432: "JKC"}
sorted_scores = sorted(leaderboard, reverse=True)
print(sorted_scores)  # [432, 231, 123]

To sort by values, you can pass leaderboard.values() or use a key function with items().

sorted_by_name = sorted(leaderboard.items(), key=lambda item: item[1])
print(sorted_by_name)  # [(123, 'ABC'), (231, 'CKL'), (432, 'JKC')]

Sorting Complex Objects

When working with custom objects, sorting requires a defined comparison. You can either use the key argument or implement special methods like __lt__ in your class.

class Book:
    def __init__(self, title, price):
        self.title = title
        self.price = price

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

books = [Book("Python 101", 25), Book("Advanced Python", 40), Book("Data Science", 30)]
sorted_books = sorted(books, key=lambda book: book.price)
print(sorted_books)  # [Python 101 ($25), Data Science ($30), Advanced Python ($40)]

This makes it easy to sort complex datasets by attributes like price, date, or name.

Sorting Tuples and Lists of Lists

Nested data structures such as tuples and lists of lists can also be sorted with sorted().

data = [(2, 'B'), (1, 'A'), (3, 'C')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)  # [(1, 'A'), (2, 'B'), (3, 'C')]

You can even sort by multiple criteria using a tuple in the key function.

Performance of Sorted in Python

The sorted() function in Python uses Timsort, a hybrid algorithm derived from merge sort and insertion sort. Its time complexity is O(n log n), making it efficient for large datasets.

Timsort adapts to real-world data by recognizing patterns, which makes it faster than traditional algorithms in many cases.

Best Practices for Using Sorted Function

  • Always use the key argument instead of complex comparison functions for readability.
  • Remember that sorted() creates a new list, preserving immutability.
  • Use list.sort() when you want in-place sorting for large datasets.
  • For case-insensitive string sorting, use key=str.lower.

Sorting in Python with Sorted Function: FAQs

1. Does the sorted() function modify the original list?

No. The sorted() function returns a new list, leaving the original unchanged. This makes it safe for immutable operations.

2. What’s the difference between sorted() and list.sort()?

sorted() works on any iterable and returns a new list. The sort() method only works on lists and modifies them in place.

3. Can I sort custom objects in Python?

Yes. You can either provide a key function to sorted() or implement comparison magic methods like __lt__ in your class.

4. How does Python handle sorting with different data types?

Numbers are sorted numerically, strings lexicographically, and custom objects need a key or defined comparison method.

5. Is Python’s sorted() function efficient for large data?

Yes. It uses Timsort with a complexity of O(n log n), optimized for real-world datasets, making it both efficient and reliable.

Scroll to Top