{
    "slug": "py_comprehension_patterns",
    "term": "Dict & Set Comprehensions",
    "category": "python",
    "difficulty": "beginner",
    "short": "Python's concise syntax for building dicts, sets, and lists in a single expression — replacing verbose for-loop accumulation patterns.",
    "long": "Comprehensions: list [expr for x in iterable if cond], dict {k: v for ...}, set {expr for ...}, generator (expr for ...). They are faster than equivalent for-loops (built-in optimisation), more readable for simple transformations, and composable. Nested comprehensions (matrix flattening) are possible but harm readability beyond two levels. Generator expressions are lazy — use when you only iterate once to avoid building the full list. dict.fromkeys() and Counter() are preferable to comprehensions for specific patterns.",
    "aliases": [
        "list comprehension",
        "dict comprehension",
        "set comprehension",
        "generator expression"
    ],
    "tags": [
        "python",
        "syntax",
        "patterns"
    ],
    "misconception": "List comprehensions are always faster than for loops — for complex bodies with multiple function calls, the performance difference is negligible; use comprehensions for readability, not micro-optimisation.",
    "why_it_matters": "Comprehensions are idiomatic Python — code that uses them reads as 'what' (transform this collection) rather than 'how' (iterate, append, check). Reviewers expect them for simple transforms.",
    "common_mistakes": [
        "Nested comprehensions with 3+ levels — break into named generators for readability.",
        "List comprehension when a generator suffices — [x for x in data] passed to sum() builds a full list; use sum(x for x in data).",
        "Complex filtering logic in comprehension conditions — extract to a named function.",
        "Mutating state inside a comprehension — comprehensions are for building new structures, not side effects."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_walrus_operator",
        "py_match_statement",
        "py_dataclasses_advanced"
    ],
    "prerequisites": [
        "py_list_comprehensions",
        "py_generators",
        "py_type_hints"
    ],
    "refs": [
        "https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions"
    ],
    "bad_code": "# Verbose for-loop patterns:\nname_map = {}\nfor user in users:\n    name_map[user.id] = user.name\n\nactive_ids = []\nfor user in users:\n    if user.is_active:\n        active_ids.append(user.id)\n\nunique_roles = set()\nfor user in users:\n    unique_roles.add(user.role)",
    "good_code": "# Concise comprehensions:\nname_map = {user.id: user.name for user in users}\n\nactive_ids = [user.id for user in users if user.is_active]\n\nunique_roles = {user.role for user in users}\n\n# Generator expression (lazy — no full list built):\ntotal = sum(order.total for order in orders if order.is_complete)\n\n# Nested — flatten matrix:\nflat = [cell for row in matrix for cell in row]",
    "quick_fix": "Use dict comprehensions to transform dicts, set comprehensions to deduplicate, and generator expressions to avoid materialising large intermediate lists",
    "severity": "low",
    "effort": "low",
    "created": "2026-03-16",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_comprehension_patterns",
        "html_url": "https://codeclaritylab.com/glossary/py_comprehension_patterns",
        "json_url": "https://codeclaritylab.com/glossary/py_comprehension_patterns.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Dict & Set Comprehensions](https://codeclaritylab.com/glossary/py_comprehension_patterns) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_comprehension_patterns"
            }
        }
    }
}