This rule raises an issue when sorted() with indexing ([0] or [-1]) is used to find the minimum or maximum value in a collection, including variants with reverse=True.

Why is this an issue?

When you need to find the smallest or largest element in a collection, you might be tempted to sort the entire collection and then access the first or last element. However, this approach is inefficient and makes your code harder to understand.

The sorted() function creates a new sorted list from all elements, an O(n log n) operation in time, plus O(n) in memory. After sorting, you only use one element and discard the rest.

Python provides built-in min() and max() functions that find the smallest or largest element in a single pass (O(n) time) with no extra memory allocation. They also make your intent immediately clear to anyone reading the code.

min(), max(), and sorted() all support an optional key parameter, so you can preserve custom comparison logic. Note that min() and max() do not have a reverse parameter, so when replacing sorted(iterable, reverse=True)[0], you should use max(iterable) instead, and vice versa for [-1].

What is the potential impact?

How to fix it

Replace sorted(iterable)[0] with min(iterable) and sorted(iterable)[-1] with max(iterable). When reverse=True is used, the mapping is inverted: sorted(iterable, reverse=True)[0] becomes max(iterable) and sorted(iterable, reverse=True)[-1] becomes min(iterable).

Code examples

Noncompliant code example

numbers = [42, 17, 93, 8, 51]
smallest = sorted(numbers)[0]  # Noncompliant

Compliant solution

numbers = [42, 17, 93, 8, 51]
smallest = min(numbers)

Noncompliant code example

numbers = [42, 17, 93, 8, 51]
largest = sorted(numbers)[-1]  # Noncompliant

Compliant solution

numbers = [42, 17, 93, 8, 51]
largest = max(numbers)

Noncompliant code example

numbers = [42, 17, 93, 8, 51]
largest = sorted(numbers, reverse=True)[0]  # Noncompliant

Compliant solution

numbers = [42, 17, 93, 8, 51]
largest = max(numbers)

Resources

Documentation