This rule raises an issue when a collection is created with the use of a lambda function inside of map().

Why is this an issue?

The map() function applies a given function to each item of an iterable. When this function is a lambda, especially a simple one, the resulting code can sometimes be less readable than its comprehension or generator expression equivalent. For example: A comprehension like [x * 2 for x in nums] is more straightforward to read and understand at a glance than list(map(lambda x: x * 2, nums)). The logic is more self-contained and doesn’t require mentally parsing the map and lambda separately.

Using map() could also have an impact on performance. While map() can be very efficient when used with built-in functions or pre-defined functions written in C, the use of a Python lambda introduces function call overhead for each element in the iterable.

How to fix it

To fix this issue replace the map(lambda …​) construct with an equivalent generator expression or a list, set, or dictionary comprehension.

nums = [1, 2, 3, 4]

list_map = list(map(lambda num: num * 2, nums)) # Noncompliant: the map and lambda function can be replaced by a list-comprehension
nums = [1, 2, 3, 4]

list_comp = [num * 2 for num in nums] # Compliant

Resources

Documentation