[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"qa-\u002Fpython\u002Fiteration\u002Fcomprehensions":3},{"page":4,"siblings":52,"blog":43},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"related":43,"seo":44,"seoDescription":45,"stem":46,"subtopic":47,"topic":48,"topicSlug":49,"updated":50,"__hash__":51},"qa\u002Fpython\u002Fiteration\u002Fcomprehensions.md","Comprehensions",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","Python","python",{},true,"\u002Fpython\u002Fiteration\u002Fcomprehensions",[22,26,30,35,39],{"id":23,"difficulty":14,"q":24,"a":25},"list-comp-syntax","What is a list comprehension and why use one?","A **list comprehension** is a concise expression that builds a list in a\nsingle readable line: `[expression for item in iterable]`. It replaces the\ncommon pattern of creating an empty list and `append`-ing in a `for` loop.\n\n```python\n# the verbose way\nsquares = []\nfor n in range(5):\n    squares.append(n * n)\n\n# the comprehension\nsquares = [n * n for n in range(5)]   # [0, 1, 4, 9, 16]\n```\n\nBeyond brevity, comprehensions are usually **faster** than an equivalent\nloop (the iteration runs in optimized C) and they signal intent: \"I'm\ntransforming a sequence into a new list.\" Reach for one whenever you're\nbuilding a list by mapping or filtering another iterable.\n",{"id":27,"difficulty":14,"q":28,"a":29},"comp-filtering","How do you filter and conditionally transform inside a comprehension?","A trailing **`if` clause filters** items — only elements for which it is\ntruthy are kept. A **conditional expression** (`x if cond else y`) goes at\nthe **front**, before the `for`, because it's part of the output expression,\nnot a filter.\n\n```python\nnums = range(6)\n\nevens = [n for n in nums if n % 2 == 0]          # filter: [0, 2, 4]\nlabels = [\"even\" if n % 2 == 0 else \"odd\"        # transform every item\n          for n in nums]                         # ['even','odd',...]\nboth = [n * 2 for n in nums if n > 2]            # filter THEN transform\n```\n\nRemember the position rule: a **filter `if`** comes after the `for`; a\n**`if\u002Felse` expression** comes before it. Mixing them up is a common\nbeginner error.\n",{"id":31,"difficulty":32,"q":33,"a":34},"nested-comp","medium","How do nested comprehensions work?","You can chain multiple `for` clauses to flatten or iterate over nested\ndata. The clauses read **left to right in the same order** as nested\nloops. You can also nest a comprehension *inside* the output expression to\nbuild a list of lists.\n\n```python\nmatrix = [[1, 2], [3, 4]]\n\nflat = [x for row in matrix for x in row]   # [1, 2, 3, 4]\n# equivalent to:\n#   for row in matrix:\n#       for x in row:\n\ngrid = [[r * c for c in range(3)] for r in range(3)]  # list of rows\n```\n\nThe trap is reading the order backwards — the **outer** loop is written\nfirst. Keep nesting shallow; two levels is usually the readability limit\nbefore a plain loop is clearer.\n",{"id":36,"difficulty":14,"q":37,"a":38},"dict-set-comp","What are dict and set comprehensions?","The same syntax works for dicts and sets. A **dict comprehension** uses\n`{key: value for ...}` and a **set comprehension** uses `{expr for ...}`\n(no colon). Sets automatically deduplicate results.\n\n```python\nnames = [\"ada\", \"grace\", \"ada\"]\n\nlengths = {n: len(n) for n in names}     # {'ada': 3, 'grace': 5}\nunique  = {n for n in names}             # {'ada', 'grace'}  (deduped)\nswapped = {v: k for k, v in lengths.items()}  # invert a dict\n```\n\nNote `{}` alone is an empty **dict**, not a set — use `set()` for an empty\nset. Dict and set comprehensions accept the same `if` filters and nested\n`for` clauses as list comprehensions.\n",{"id":40,"difficulty":32,"q":41,"a":42},"comp-vs-map-filter","When should you NOT use a comprehension?","Comprehensions are for **building a collection**. Avoid them when you only\nwant **side effects** (printing, writing to a DB) — that abuse hides intent\nand builds a throwaway list. Use a plain `for` loop instead. Also skip them\nwhen the logic is so complex that the line becomes unreadable.\n\n```python\n# bad: comprehension purely for side effects\n[print(x) for x in items]      # builds a useless list of Nones\n\n# good: a loop says \"do this for each\"\nfor x in items:\n    print(x)\n```\n\nComprehensions overlap with `map`\u002F`filter`, but are usually more readable\nand avoid `lambda`. Prefer a generator expression `(...)` over a list comp\nwhen you only iterate once and don't need to materialize the whole result.\n",null,{"description":11},"Python interview questions on list, dict, and set comprehensions, filtering with if, conditional expressions, nested comprehensions, and when not to use them.","python\u002Fiteration\u002Fcomprehensions","List, Dict & Set Comprehensions","Comprehensions & Iteration","iteration","2026-06-18","uGKkZQVAIauWnty3ubl1uoueazHZ0xd5yzGpbq2r5x4",[53,57,58,62],{"subtopic":54,"path":55,"order":56},"Generators & yield","\u002Fpython\u002Fiteration\u002Fgenerators",1,{"subtopic":47,"path":20,"order":12},{"subtopic":59,"path":60,"order":61},"Iterators & the Iterator Protocol","\u002Fpython\u002Fiteration\u002Fiterators",3,{"subtopic":63,"path":64,"order":65},"enumerate, zip & Unpacking","\u002Fpython\u002Fiteration\u002Fenumerate-zip",4,1781808679841]