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.
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].
min() or max() take only O(n). For
large collections, this difference results in noticeably slower execution.sorted() creates a new list containing all elements. min() and max()
only store a single element during execution.sorted()[0] to find a minimum value obscures the intent of the code.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).
numbers = [42, 17, 93, 8, 51] smallest = sorted(numbers)[0] # Noncompliant
numbers = [42, 17, 93, 8, 51] smallest = min(numbers)
numbers = [42, 17, 93, 8, 51] largest = sorted(numbers)[-1] # Noncompliant
numbers = [42, 17, 93, 8, 51] largest = max(numbers)
numbers = [42, 17, 93, 8, 51] largest = sorted(numbers, reverse=True)[0] # Noncompliant
numbers = [42, 17, 93, 8, 51] largest = max(numbers)
min() built-in functionmax() built-in functionsorted() built-in function