Skip to content

unnecessary-comprehension (C416)#

Derived from the flake8-comprehensions linter.

Fix is always available.

What it does#

Checks for unnecessary dict, list, and set comprehension.

Why is this bad?#

It's unnecessary to use a dict/list/set comprehension to build a data structure if the elements are unchanged. Wrap the iterable with dict(), list(), or set() instead.

Examples#

{a: b for a, b in iterable}
[x for x in iterable]
{x for x in iterable}

Use instead:

dict(iterable)
list(iterable)
set(iterable)

Fix safety#

This rule's fix is marked as unsafe, as it may occasionally drop comments when rewriting the comprehension. In most cases, though, comments will be preserved.