[{"data":1,"prerenderedAt":74},["ShallowReactive",2],{"qa-\u002Fpython\u002Fdata-structures\u002Fsets":3},{"page":4,"siblings":57,"blog":48},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":48,"seo":49,"seoDescription":50,"stem":51,"subtopic":52,"topic":53,"topicSlug":54,"updated":55,"__hash__":56},"qa\u002Fpython\u002Fdata-structures\u002Fsets.md","Sets",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,4,"\u002Fpython\u002Fdata-structures\u002Fsets",[23,28,32,36,40,44],{"id":24,"difficulty":25,"q":26,"a":27},"set-operations","easy","What are the main set operations in Python?","Sets support the classic mathematical operations, each with an **operator** and\nan equivalent **method**: **union** (`|`), **intersection** (`&`),\n**difference** (`-`), and **symmetric difference** (`^`, items in exactly one\nset).\n\n```python\na = {1, 2, 3}\nb = {2, 3, 4}\n\na | b    # {1, 2, 3, 4}      union — in either\na & b    # {2, 3}            intersection — in both\na - b    # {1}               difference — in a, not b\na ^ b    # {1, 4}            symmetric difference — in one, not both\n\na.union(b)              # method form, accepts any iterable\na.intersection([2, 3])  # b can be a list here\n```\n\nThe **operator** forms require both operands to be sets, while the **method**\nforms accept any iterable. Use them for fast \"what's common \u002F unique \u002F missing\"\nquestions instead of nested loops.\n",{"id":29,"difficulty":14,"q":30,"a":31},"set-vs-list-membership","Why is membership testing faster in a set than a list?","A `set` is backed by a **hash table**, so `x in s` is **average O(1)** — it\nhashes `x` and checks one bucket. A `list` has no such index, so `x in lst` is\n**O(n)** — it scans elements one by one until it finds a match or reaches the\nend.\n\n```python\nbig_list = list(range(1_000_000))\nbig_set  = set(big_list)\n\n999_999 in big_list   # O(n) — scans up to a million items\n999_999 in big_set    # O(1) — single hash lookup\n```\n\nFor repeated membership checks over a large collection, converting to a set\nfirst is a huge win. The trade-off is that sets are **unordered** and elements\nmust be **hashable**. Rule of thumb: if you mostly ask \"is X in here?\", use a\nset, not a list.\n",{"id":33,"difficulty":25,"q":34,"a":35},"dedup-with-set","How do you remove duplicates from a list using a set?","Wrapping a list in **`set()`** removes duplicates instantly, since a set can't\nhold repeated values. The catch is that a set is **unordered**, so this doesn't\npreserve the original order.\n\n```python\nnums = [3, 1, 2, 3, 1]\nunique = list(set(nums))      # e.g. [1, 2, 3] — order NOT guaranteed\n\n# order-preserving dedup (dict keys are unique AND ordered since 3.7):\nordered = list(dict.fromkeys(nums))   # [3, 1, 2]\n```\n\nUse `set()` when you only care about the **distinct values**; when order\nmatters, use **`dict.fromkeys()`**, which keeps first-seen order thanks to\nguaranteed dict ordering. Both require the elements to be hashable.\n",{"id":37,"difficulty":25,"q":38,"a":39},"add-discard-remove","What is the difference between add, discard, and remove on a set?","**`add(x)`** inserts an element (a no-op if it's already present). To delete,\n**`remove(x)`** raises `KeyError` if the element is missing, while\n**`discard(x)`** removes it **silently** if present and does nothing otherwise.\n\n```python\ns = {1, 2, 3}\ns.add(2)          # already there — no change\ns.add(4)          # {1, 2, 3, 4}\n\ns.remove(4)       # {1, 2, 3}\ns.remove(99)      # KeyError — not in set\ns.discard(99)     # no error, no change\ns.pop()           # removes and returns an arbitrary element\n```\n\nChoose **`discard`** when \"remove if it's there\" is the intent (no need to guard\nwith a membership check), and **`remove`** when a missing element is genuinely an\nerror you want surfaced. `pop()` removes an arbitrary element since sets are\nunordered.\n",{"id":41,"difficulty":14,"q":42,"a":43},"frozenset","What is a frozenset and when do you need one?","A **`frozenset`** is the **immutable** version of `set` — it supports all the\nread operations (union, intersection, membership) but has **no `add`\u002F`remove`**.\nBecause it's immutable, it's **hashable**, so it can be a **dict key** or an\n**element of another set**.\n\n```python\nfs = frozenset([1, 2, 3])\nfs.add(4)              # AttributeError — immutable\nfs & {2, 3, 4}         # frozenset({2, 3}) — set ops still work\n\n{fs: \"a group\"}        # usable as a dict key\n{frozenset({1, 2}), frozenset({3, 4})}   # a set OF sets\n```\n\nThe classic use is a **set of sets**: regular sets are unhashable, so the inner\nones must be frozensets. Also use a frozenset for a constant collection you want\nto guarantee can't be mutated. Reach for it whenever you need a set-like value\nthat must be hashable.\n",{"id":45,"difficulty":25,"q":46,"a":47},"set-comprehension","What is a set comprehension?","A **set comprehension** builds a set in one expression with\n`{expr for item in iterable}`, automatically **deduplicating** the results. It's\nthe set sibling of list and dict comprehensions, with curly braces and no\n`key:value` pair.\n\n```python\nsquares = {n * n for n in range(-3, 4)}\n# {0, 1, 4, 9} — note 9 appears once even though -3 and 3 both map to it\n\nwords = [\"Hi\", \"hi\", \"HEY\"]\nlowered = {w.lower() for w in words}   # {'hi', 'hey'}\n```\n\nIt's ideal when you want **unique transformed values** in a single readable step.\nWatch out that `{}` alone is an **empty dict**, not an empty set — use `set()`\nfor an empty set. Use a set comprehension when both transformation and\ndeduplication are the goal.\n",null,{"description":11},"Python interview questions on set operations, O(1) membership vs lists, deduplication, add\u002Fdiscard\u002Fremove, frozensets, and set comprehensions.","python\u002Fdata-structures\u002Fsets","Sets & Frozensets","Data Structures","data-structures","2026-06-18","cTcBrrIA7tgVyW4p3hQf_V6QjLhZcf7eBJuL-k_iHL0",[58,62,65,69,70],{"subtopic":59,"path":60,"order":61},"Lists & Slicing","\u002Fpython\u002Fdata-structures\u002Flists",1,{"subtopic":63,"path":64,"order":12},"Tuples & Named Tuples","\u002Fpython\u002Fdata-structures\u002Ftuples",{"subtopic":66,"path":67,"order":68},"Dictionaries","\u002Fpython\u002Fdata-structures\u002Fdictionaries",3,{"subtopic":52,"path":21,"order":20},{"subtopic":71,"path":72,"order":73},"The collections Module","\u002Fpython\u002Fdata-structures\u002Fcollections-module",5,1781808679480]