This rule raises an issue when the functions list(), tuple(), set(), sorted(), or reversed() are unnecessarily wrapped around each other’s return values or used to convert values that don’t require conversion.

Why is this an issue?

Python’s built-in functions for processing iterables such as list(), tuple(), set(), sorted(), and reversed() are designed to accept any iterable as input. When these functions are unnecessarily nested within each other, it creates redundant operations that add unnecessary computational overhead by creating intermediate data structures, decrease code readability and make the intention less clear, and waste memory by duplicating data structures temporarily.

How to fix it

When the outer function is given a collection but could have been given an iterable, the unnecessary conversion should be removed. For example, in sorted(list(iterable)), the outer sorted() function can accept an iterable directly, so the inner list() call is redundant and should be removed.

When the function sorted() is wrapped with list(), remove this conversion operation, since sorted() already returns a list.

Code examples

Noncompliant code example

iterable = (3, 1, 4, 1)

sorted_of_list = list(sorted(iterable)) # Noncompliant

Compliant solution

iterable = (3, 1, 4, 1)

sorted_of_list = sorted(iterable)

Resources

Documentation