{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "83f5f63e",
   "metadata": {},
   "source": [
    "# Sets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1b3db3f7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.241984Z",
     "iopub.status.busy": "2026-10-13T02:30:20.241893Z",
     "iopub.status.idle": "2026-10-13T02:30:20.483201Z",
     "shell.execute_reply": "2026-10-13T02:30:20.482967Z"
    },
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent  # ← Add project root, not chapters\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle, structshape\n",
    "from shared.download import download\n",
    "\n",
    "# Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a92a27b3",
   "metadata": {},
   "source": [
    "A set holds unique values with no order, which makes it the right tool for removing duplicates, testing membership, and comparing collections. This section covers what sets are, which values a set can hold, how to create and use sets, and the set operations union, intersection, and difference."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc67e307",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0eafbe4e",
   "metadata": {},
   "source": [
    "## What Sets Are\n",
    "\n",
    "A set is an **unordered** collection of unique values. Unlike lists or tuples, sets do not allow **duplicates**, and the elements have no guaranteed order. \n",
    "\n",
    "Here below is an example of a set. Note that it uses curly braces just like dictionaries. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68035ac0",
   "metadata": {},
   "source": [
    "```{index} set, unordered collection, unique elements\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ccf867f4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.484305Z",
     "iopub.status.busy": "2026-10-13T02:30:20.484214Z",
     "iopub.status.idle": "2026-10-13T02:30:20.485687Z",
     "shell.execute_reply": "2026-10-13T02:30:20.485493Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n"
     ]
    }
   ],
   "source": [
    "s = {1, 2, 3, 3, 2}\n",
    "print(s)                ### {1, 2, 3}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aac530ad",
   "metadata": {},
   "source": [
    "Sets are useful when you care about **membership**: whether something is **in** a collection; rather than order or position.\n",
    "\n",
    "The most common use cases are:\n",
    "\n",
    "- Removing duplicates from a list\n",
    "- Checking membership quickly\n",
    "- Comparing two collections (what's shared, what's different)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "352d5069",
   "metadata": {},
   "source": [
    "For sets, the four key properties that make sets different from other data structures:\n",
    "\n",
    "1. **Unordered**: Elements have no guaranteed position. There is no first or last element.\n",
    "2. **Unique**: Duplicates are automatically removed.\n",
    "3. **Mutable**: You can add and remove elements.\n",
    "4. **Hashable elements only**: Every element must be hashable. Strings and numbers work; tuples work only when every element is hashable. Lists, dictionaries, and sets do not work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "abf76b98",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.486478Z",
     "iopub.status.busy": "2026-10-13T02:30:20.486413Z",
     "iopub.status.idle": "2026-10-13T02:30:20.488490Z",
     "shell.execute_reply": "2026-10-13T02:30:20.488336Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1. Sets are unordered, so the order of elements is not guaranteed.\n",
    "{3, 1, 2} == {1, 2, 3}  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0120dc41",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.489332Z",
     "iopub.status.busy": "2026-10-13T02:30:20.489252Z",
     "iopub.status.idle": "2026-10-13T02:30:20.490765Z",
     "shell.execute_reply": "2026-10-13T02:30:20.490631Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2. Sets do not allow duplicate elements, so duplicates are automatically removed.\n",
    "{1, 2, 2, 3, 3}         # {1, 2, 3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c6ebf262",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.491506Z",
     "iopub.status.busy": "2026-10-13T02:30:20.491454Z",
     "iopub.status.idle": "2026-10-13T02:30:20.492924Z",
     "shell.execute_reply": "2026-10-13T02:30:20.492781Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 3, 4}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3. Sets are mutable, so you can add or remove elements after the set is created.\n",
    "s = {1, 2, 3}\n",
    "s.add(4)                # works\n",
    "s.remove(2)             # works\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0d3cb961",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.493603Z",
     "iopub.status.busy": "2026-10-13T02:30:20.493548Z",
     "iopub.status.idle": "2026-10-13T02:30:20.495224Z",
     "shell.execute_reply": "2026-10-13T02:30:20.495092Z"
    }
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'list'",
     "output_type": "error",
     "traceback": [
      "\u001b[31mTypeError\u001b[39m\u001b[31m:\u001b[39m unhashable type: 'list'\n"
     ]
    }
   ],
   "source": [
    "%%expect TypeError\n",
    "### 4. Sets can contain only hashable elements, so you cannot include lists or other sets as elements.\n",
    "{1, \"hello\", (1, 2)}    # valid\n",
    "{[1, 2], [3, 4]}        # TypeError\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7abd8fd8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.495956Z",
     "iopub.status.busy": "2026-10-13T02:30:20.495892Z",
     "iopub.status.idle": "2026-10-13T02:30:20.497227Z",
     "shell.execute_reply": "2026-10-13T02:30:20.497044Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Deduplicate Course Codes *(basic)*\n",
    "# The list below contains repeated course codes.\n",
    "# 1. Build a set of unique codes.\n",
    "# 2. Print the unique set.\n",
    "# 3. Print how many distinct course codes appear.\n",
    "course_codes = [\"PY\", \"DS\", \"PY\", \"SQL\", \"DS\", \"AI\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6c7d86e9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.498020Z",
     "iopub.status.busy": "2026-10-13T02:30:20.497968Z",
     "iopub.status.idle": "2026-10-13T02:30:20.499381Z",
     "shell.execute_reply": "2026-10-13T02:30:20.499202Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'SQL', 'AI', 'PY', 'DS'}\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "course_codes = [\"PY\", \"DS\", \"PY\", \"SQL\", \"DS\", \"AI\"]\n",
    "unique_codes = set(course_codes)\n",
    "print(unique_codes)\n",
    "print(len(unique_codes))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0fd5117",
   "metadata": {},
   "source": [
    "### Choosing the Right Structure\n",
    "\n",
    "| Need                                   | Use         |\n",
    "|----------------------------------------|-------------|\n",
    "| Ordered collection, duplicates allowed | `list`      |\n",
    "| Fixed data, multiple return values     | `tuple`     |\n",
    "| Key-value lookup                       | `dict`      |\n",
    "| Unique items, membership testing       | `set`       |\n",
    "| Hashable set (dict key, nested set)    | `frozenset` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a35f0db4",
   "metadata": {},
   "source": [
    "### Hashable vs. Mutable Values\n",
    "\n",
    "Mutability describes whether an object can change. Hashability describes whether it has a stable hash and equality behavior suitable for dictionary keys and set elements. These are distinct properties. \n",
    "\n",
    "- **Hashable** means an object has a hash value that stays stable during its lifetime, and equal objects have equal hashes.\n",
    "- The built-in mutable containers `list`, `dict`, and `set` are **not hashable**. Some user-defined mutable objects are hashable by identity.\n",
    "- **Immutable** objects are often hashable (for example: `int`, `float`, `str`, `tuple`), but for tuples, all nested elements must also be hashable.\n",
    "- For hash-table types: `dict` requires **hashable keys**, and `set` requires **hashable elements**.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e9565e6",
   "metadata": {},
   "source": [
    "```{index} hashable, mutable; set elements\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7e49497",
   "metadata": {},
   "source": [
    "### Hashability\n",
    "\n",
    "Let us compare **set**, **list**, and **dict** and this time focus on hashability. \n",
    "\n",
    "\n",
    "| Feature      | Set                    | List          | Dict                          |\n",
    "|--------------|------------------------|---------------|-------------------------------|\n",
    "| Ordered      | **No**                     | Yes           | Yes (insertion order)         |\n",
    "| Duplicates   | **No**                     | Yes           | Keys: No, Values: Yes         |\n",
    "| Mutable      | **Yes**                    | Yes           | Yes                           |\n",
    "| Allows only **hashable** elements | Yes   | No            | Keys only                     |\n",
    "| Lookup speed | Avg O(1)               | O(n)          | Avg O(1)                      |\n",
    "| Use case     | Unique items, membership | Ordered items | Key-value pairs               |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c7e49497",
   "metadata": {},
   "source": [
    "```{index} hashable, hash function, hash()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17099ee3",
   "metadata": {},
   "source": [
    "In computer science, hashable means that an object can be converted into a fixed-size integer (called a hash value or hash code) via a hash function. This hash value is used to quickly locate the object in data structures like hash tables, dictionaries, and sets. For something to be hashable, it generally needs to satisfy two properties:\n",
    "\n",
    "- **Consistency**: the hash value must not change during the object's lifetime. Built-in lists, dictionaries, and sets are unhashable. Mutability alone does not determine hashability for every Python object.\n",
    "- **Equality consistency**: if two objects are considered equal (`a == b`), they must have the same hash value. The reverse isn't required; two different objects can share a hash (called a collision), but equal objects must hash identically.\n",
    "\n",
    "Hash-based data structures like hash maps and hash sets rely on hash values to place and find items in O(1) average time. If you want to use an object as a dictionary key or store it in a set, it needs to be hashable.\n",
    "\n",
    "In summary, **hashable** means you can be consistently fingerprinted with a number, which is the prerequisite for being usable as a key in fast lookup structures."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "630069ed",
   "metadata": {},
   "source": [
    "```text\n",
    "key     →  hash function    →  index  →  bucket in array\n",
    "\"cat\"   →  hash(\"cat\")      →  42     →  array[42]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0f675460",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.500096Z",
     "iopub.status.busy": "2026-10-13T02:30:20.500038Z",
     "iopub.status.idle": "2026-10-13T02:30:20.501343Z",
     "shell.execute_reply": "2026-10-13T02:30:20.501195Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4330246517638682750\n",
      "6754848497972444991\n",
      "4330246517638682750\n"
     ]
    }
   ],
   "source": [
    "print(hash(\"cat\"))           ### -9223372036854775808\n",
    "print(hash(\"dog\"))           ### -867955804616931492\n",
    "print(hash(\"cat\"))           ### -9223372036854775808"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "654c7020",
   "metadata": {},
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98e2455a",
   "metadata": {},
   "source": [
    "## Creating Sets and Testing Membership\n",
    "\n",
    "A set is created using curly braces `{}` with comma-separated values, or by using the `set()` constructor. \n",
    "\n",
    "Unlike lists, sets are unordered and do not allow duplicates - if you add the same value twice, it only appears once. This makes sets useful for storing **unique** items. One important gotcha: an empty {} creates a dict, not a set - you must use set() for an empty set.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-98e2455a",
   "metadata": {},
   "source": [
    "```{index} set() constructor, set literal, empty set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "41d69110",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.502070Z",
     "iopub.status.busy": "2026-10-13T02:30:20.502022Z",
     "iopub.status.idle": "2026-10-13T02:30:20.503440Z",
     "shell.execute_reply": "2026-10-13T02:30:20.503290Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n",
      "{1, 2, 3}\n"
     ]
    }
   ],
   "source": [
    "s = {1, 2, 3, 3}       # duplicate 3 is ignored\n",
    "print(s)               # {1, 2, 3}\n",
    "\n",
    "s = set([1, 2, 2, 3])  # from a list\n",
    "print(s)               # {1, 2, 3}\n",
    "\n",
    "s = set()              # empty set\n",
    "d = {}                 # this is a dict, not a set!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54e54710",
   "metadata": {},
   "source": [
    "`set` elements must be **hashable**. Since sets use **hashing** internally to enforce uniqueness and enable fast lookup, all elements must be hashable. This means you can store integers, floats, strings, and tuples of hashable elements in a set, but not lists or dictionaries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f488cd39",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.504095Z",
     "iopub.status.busy": "2026-10-13T02:30:20.504054Z",
     "iopub.status.idle": "2026-10-13T02:30:20.505545Z",
     "shell.execute_reply": "2026-10-13T02:30:20.505405Z"
    }
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'list'",
     "output_type": "error",
     "traceback": [
      "\u001b[31mTypeError\u001b[39m\u001b[31m:\u001b[39m unhashable type: 'list'\n"
     ]
    }
   ],
   "source": [
    "%%expect TypeError\n",
    "# Valid\n",
    "s = {1, \"hello\", (1, 2)}\n",
    "\n",
    "# Invalid\n",
    "s = {[1, 2], [3, 4]}    # TypeError: unhashable type: 'list'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17f4f5e2",
   "metadata": {},
   "source": [
    "Similarly, a `tuple` is hashable only if **all** of its elements are hashable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ab98e372",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.506296Z",
     "iopub.status.busy": "2026-10-13T02:30:20.506254Z",
     "iopub.status.idle": "2026-10-13T02:30:20.507665Z",
     "shell.execute_reply": "2026-10-13T02:30:20.507527Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-3550055125485641917\n",
      "7267574591690527098\n",
      "unhashable type: 'list'\n"
     ]
    }
   ],
   "source": [
    "print(hash((1, 2)))          # ok\n",
    "print(hash((1, (2, 3))))     # ok\n",
    "\n",
    "try:\n",
    "    hash((1, [2, 3]))        # list inside tuple => unhashable\n",
    "except TypeError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b005023",
   "metadata": {},
   "source": [
    "### Accessing and Iterating\n",
    "\n",
    "Sets have no indexing or positional access. Because sets are unordered, there's no concept of \"first\" or \"second\" element, so index access makes no sense. \n",
    "\n",
    "Compared with list and dictionary, `dict` is the only one with a built-in safe getter. A `list` requires a **guard clause**. \n",
    "\n",
    "| | List | Dict | Set |\n",
    "|---|---|---|---|\n",
    "| **Access** | by index `l[i]` | by key `d[key]` | no direct access |\n",
    "| **Safe get** | `l[i] if i < len(l) else default` | `d.get(key, default)` | `val if val in s else default` |\n",
    "| **Built-in safe method** | none | `.get()` | none |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3574b55d",
   "metadata": {},
   "source": [
    "```{index} set; accessing elements\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "cf593cd9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.508378Z",
     "iopub.status.busy": "2026-10-13T02:30:20.508337Z",
     "iopub.status.idle": "2026-10-13T02:30:20.509989Z",
     "shell.execute_reply": "2026-10-13T02:30:20.509855Z"
    }
   },
   "outputs": [
    {
     "ename": "IndexError",
     "evalue": "list index out of range",
     "output_type": "error",
     "traceback": [
      "\u001b[31mIndexError\u001b[39m\u001b[31m:\u001b[39m list index out of range\n"
     ]
    }
   ],
   "source": [
    "%%expect IndexError\n",
    "d = {'x': 1, 'y': 2}\n",
    "d.get('z', 'not found')                 # 'not found' — no error\n",
    "\n",
    "l = [10, 20, 30]\n",
    "l[5]                                  # IndexError!   ### uncomment to see the error\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78699f53",
   "metadata": {},
   "source": [
    "For `list`, a safe way to handle a possible out-of-range error is to use a guard clause. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "4fa18963",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.510696Z",
     "iopub.status.busy": "2026-10-13T02:30:20.510651Z",
     "iopub.status.idle": "2026-10-13T02:30:20.511977Z",
     "shell.execute_reply": "2026-10-13T02:30:20.511811Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "l = [10, 20, 30]\n",
    "\n",
    "result = l[5] if 5 < len(l) else None   # None — safe\n",
    "print(result)                           # None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eae58e00",
   "metadata": {},
   "source": [
    "To work with elements in a set, you can:\n",
    "\n",
    "| Method | Example | Notes |\n",
    "|---|---|---|\n",
    "| **Membership check** | `3 in s` | True/False only, no error |\n",
    "| **Iterate** | `for x in s:` | no guaranteed order |\n",
    "| **Convert to list** | `list(s)[0]` | order not guaranteed |\n",
    "| **`s.pop()`** | `s.pop()` | returns an arbitrary element |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "dfd96d28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.512805Z",
     "iopub.status.busy": "2026-10-13T02:30:20.512750Z",
     "iopub.status.idle": "2026-10-13T02:30:20.514037Z",
     "shell.execute_reply": "2026-10-13T02:30:20.513837Z"
    }
   },
   "outputs": [],
   "source": [
    "### check membership\n",
    "\n",
    "if \"apple\" in s:\n",
    "    print(\"found\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4f9c90f9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.514741Z",
     "iopub.status.busy": "2026-10-13T02:30:20.514699Z",
     "iopub.status.idle": "2026-10-13T02:30:20.515982Z",
     "shell.execute_reply": "2026-10-13T02:30:20.515835Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "(1, 2)\n",
      "hello\n"
     ]
    }
   ],
   "source": [
    "### iterate over a set\n",
    "for element in s:\n",
    "    print(element)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "cb1e1a08",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.516656Z",
     "iopub.status.busy": "2026-10-13T02:30:20.516604Z",
     "iopub.status.idle": "2026-10-13T02:30:20.517795Z",
     "shell.execute_reply": "2026-10-13T02:30:20.517642Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, (1, 2), 'hello']\n"
     ]
    }
   ],
   "source": [
    "### conversion to list\n",
    "l = list(s)\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "288f4af5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.518462Z",
     "iopub.status.busy": "2026-10-13T02:30:20.518417Z",
     "iopub.status.idle": "2026-10-13T02:30:20.519893Z",
     "shell.execute_reply": "2026-10-13T02:30:20.519737Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### s.pop() removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError.\n",
    "s = {1, 2, 3}\n",
    "s.pop()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25b8fe1b",
   "metadata": {},
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "0df2b4d9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.520589Z",
     "iopub.status.busy": "2026-10-13T02:30:20.520546Z",
     "iopub.status.idle": "2026-10-13T02:30:20.521811Z",
     "shell.execute_reply": "2026-10-13T02:30:20.521640Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Membership-Heavy Search *(applied)*\n",
    "# Use a set when you need many membership checks.\n",
    "# 1. Convert allowed_users to a set.\n",
    "# 2. Print each login name that is allowed.\n",
    "allowed_users = [\"maya\", \"li\", \"ana\", \"sam\"]\n",
    "login_attempts = [\"eli\", \"maya\", \"sam\", \"zoe\", \"ana\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "0a14b5dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.522524Z",
     "iopub.status.busy": "2026-10-13T02:30:20.522477Z",
     "iopub.status.idle": "2026-10-13T02:30:20.523889Z",
     "shell.execute_reply": "2026-10-13T02:30:20.523760Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "maya\n",
      "sam\n",
      "ana\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "allowed_users = [\"maya\", \"li\", \"ana\", \"sam\"]\n",
    "login_attempts = [\"eli\", \"maya\", \"sam\", \"zoe\", \"ana\"]\n",
    "allowed = set(allowed_users)\n",
    "\n",
    "for name in login_attempts:\n",
    "    if name in allowed:\n",
    "        print(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22161c76",
   "metadata": {},
   "source": [
    "## Set Algebra\n",
    "\n",
    "Sets support mathematical operations that make it easy to compare two collections. Each operation has both an operator shorthand and a method form which produce the same result:\n",
    "\n",
    "| Operation            | Operator | Method                       | Description                                      |\n",
    "|----------------------|----------|------------------------------|--------------------------------------------------|\n",
    "| Union                | `a \\| b`  | `a.union(b)`                 | All elements from both sets                      |\n",
    "| Intersection         | `a & b`  | `a.intersection(b)`          | Only elements common to both sets                |\n",
    "| Difference           | `a - b`  | `a.difference(b)`            | Elements in `a` but not in `b`                   |\n",
    "| Symmetric Difference | `a ^ b`  | `a.symmetric_difference(b)`  | Elements in either set, but not in both          |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-22161c76",
   "metadata": {},
   "source": [
    "```{index} set algebra, set operator\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea5b55f1",
   "metadata": {},
   "source": [
    "Read each operation as a membership rule. For `a = {1, 2, 3}` and `b = {3, 4, 5}`, the shared element is `3`:\n",
    "\n",
    "| Element | In a? | In b? | Union: either | Intersection: both | a - b: a only | Symmetric difference: exactly one |\n",
    "| --- | --- | --- | --- | --- | --- | --- |\n",
    "| 1 | Yes | No | Keep | Omit | Keep | Keep |\n",
    "| 2 | Yes | No | Keep | Omit | Keep | Keep |\n",
    "| 3 | Yes | Yes | Keep | Keep | Omit | Omit |\n",
    "| 4 | No | Yes | Keep | Omit | Omit | Keep |\n",
    "| 5 | No | Yes | Keep | Omit | Omit | Keep |\n",
    "\n",
    "Difference has a direction: `a - b` keeps `1` and `2`, while `b - a` keeps `4` and `5`. Predict each result from the table before running the examples. These algebra operations create new sets and leave the inputs unchanged.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "3b9dae9b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.524564Z",
     "iopub.status.busy": "2026-10-13T02:30:20.524524Z",
     "iopub.status.idle": "2026-10-13T02:30:20.525735Z",
     "shell.execute_reply": "2026-10-13T02:30:20.525589Z"
    }
   },
   "outputs": [],
   "source": [
    "a = {1, 2, 3}\n",
    "b = {3, 4, 5}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7ff8e79",
   "metadata": {},
   "source": [
    "Note that, **operator** forms (`|`, `&`, `-`, `^`) require **set operands**. Method forms are more flexible and can take any iterable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "b74eae75",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.526396Z",
     "iopub.status.busy": "2026-10-13T02:30:20.526356Z",
     "iopub.status.idle": "2026-10-13T02:30:20.527680Z",
     "shell.execute_reply": "2026-10-13T02:30:20.527540Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5}\n",
      "unsupported operand type(s) for |: 'set' and 'list'\n"
     ]
    }
   ],
   "source": [
    "print(a.union([3, 4, 5]))    # works: method accepts iterable\n",
    "\n",
    "try:\n",
    "    a | [3, 4, 5]            # TypeError: right side is a list\n",
    "except TypeError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27d1077e",
   "metadata": {},
   "source": [
    "### Union \n",
    "\n",
    "All elements from both sets"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4c30589",
   "metadata": {},
   "source": [
    "```{index} union; set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "aeafeb88",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.528435Z",
     "iopub.status.busy": "2026-10-13T02:30:20.528375Z",
     "iopub.status.idle": "2026-10-13T02:30:20.530026Z",
     "shell.execute_reply": "2026-10-13T02:30:20.529840Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a | b        # {1, 2, 3, 4, 5}\n",
    "a.union(b)   # same"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "083b51d6",
   "metadata": {},
   "source": [
    "### Intersection\n",
    "\n",
    "Only elements in both sets."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a51c2ad",
   "metadata": {},
   "source": [
    "```{index} intersection; set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "aef3bac1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.530798Z",
     "iopub.status.busy": "2026-10-13T02:30:20.530751Z",
     "iopub.status.idle": "2026-10-13T02:30:20.532239Z",
     "shell.execute_reply": "2026-10-13T02:30:20.532071Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{3}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a & b              # {3}\n",
    "a.intersection(b)  # same"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ebb441c",
   "metadata": {},
   "source": [
    "### Difference\n",
    "\n",
    "Elements in a but not in b\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2a02b62",
   "metadata": {},
   "source": [
    "```{index} difference; set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "74da1325",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.532943Z",
     "iopub.status.busy": "2026-10-13T02:30:20.532903Z",
     "iopub.status.idle": "2026-10-13T02:30:20.534300Z",
     "shell.execute_reply": "2026-10-13T02:30:20.534160Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2}"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a - b              # {1, 2}\n",
    "a.difference(b)    # same"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f538100",
   "metadata": {},
   "source": [
    "### Symmetric Difference\n",
    "\n",
    "Elements in either set, but not both"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc604a40",
   "metadata": {},
   "source": [
    "```{index} symmetric difference\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "64af9751",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.534986Z",
     "iopub.status.busy": "2026-10-13T02:30:20.534939Z",
     "iopub.status.idle": "2026-10-13T02:30:20.536457Z",
     "shell.execute_reply": "2026-10-13T02:30:20.536321Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 4, 5}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a ^ b                       # {1, 2, 4, 5}\n",
    "a.symmetric_difference(b)   # same"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "e2a1f2d8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.537155Z",
     "iopub.status.busy": "2026-10-13T02:30:20.537113Z",
     "iopub.status.idle": "2026-10-13T02:30:20.538221Z",
     "shell.execute_reply": "2026-10-13T02:30:20.538092Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Basic Set Operations\n",
    "# 1. Create A = {1, 2, 3, 4} and B = {3, 4, 5, 6}.\n",
    "# 2. Print A | B, A & B, A - B, and A ^ B.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "f17f5d63",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.538923Z",
     "iopub.status.busy": "2026-10-13T02:30:20.538869Z",
     "iopub.status.idle": "2026-10-13T02:30:20.540470Z",
     "shell.execute_reply": "2026-10-13T02:30:20.540319Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Union: {1, 2, 3, 4, 5, 6}\n",
      "Intersection: {3, 4}\n",
      "Difference A-B: {1, 2}\n",
      "Symmetric Difference: {1, 2, 5, 6}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "A = {1, 2, 3, 4}\n",
    "B = {3, 4, 5, 6}\n",
    "\n",
    "print(\"Union:\", A | B)\n",
    "print(\"Intersection:\", A & B)\n",
    "print(\"Difference A-B:\", A - B)\n",
    "print(\"Symmetric Difference:\", A ^ B)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "649b3f5a",
   "metadata": {},
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19982422",
   "metadata": {},
   "source": [
    "## Mutating Sets Safely\n",
    "\n",
    "Python sets have methods for adding, removing, and checking elements.\n",
    "\n",
    "| Method             | Description                                   |\n",
    "|--------------------|-----------------------------------------------|\n",
    "| `.add(x)`          | Adds a single element                         |\n",
    "| `.update(iterable)`| Adds multiple elements                        |\n",
    "| `.copy()`       | Returns a shallow copy of the set  |\n",
    "| `.remove(x)`       | Removes element, raises `KeyError` if missing |\n",
    "| `.discard(x)`      | Removes element, silent if missing            |\n",
    "| `.pop()`           | Removes and returns an arbitrary element      |\n",
    "| `.clear()`         | Empties the set                               |\n",
    "| `.issubset(s)`     | Returns `True` if all elements are in `s`     |\n",
    "| `.issuperset(s)`   | Returns `True` if set contains all of `s`     |\n",
    "| `.isdisjoint(s)`   | Returns `True` if no elements in common       |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-19982422",
   "metadata": {},
   "source": [
    "```{index} set methods, set.clear()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40b211f3",
   "metadata": {},
   "source": [
    "### Mutability"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-40b211f3",
   "metadata": {},
   "source": [
    "```{index} mutability, in-place method\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb38a8c3",
   "metadata": {},
   "source": [
    "For the property of mutability, let's have a look over the general data structures. For in-place change methods for the common data structures, here is a comparison table. Tuple and strings are immutable, so there's no methods available for the purpose.\n",
    "\n",
    "| Method                              | List | Dict | Set | Tuple | String |\n",
    "|-------------------------------------|------|------|-----|-------|--------|\n",
    "| `.append(x)`                        | ✓    |      |     |       |        |\n",
    "| `.insert(i, x)`                     | ✓    |      |     |       |        |\n",
    "| `.extend(iter)`                     | ✓    |      |     |       |        |\n",
    "| `.update(other)`                    |      | ✓    | ✓   |       |        |\n",
    "| `.remove(x)`                        | ✓    |      | ✓   |       |        |\n",
    "| `.pop()`                            | ✓    | ✓    | ✓   |       |        |\n",
    "| `.popitem()`                        |      | ✓    |     |       |        |\n",
    "| `.add(x)`                           |      |      | ✓   |       |        |\n",
    "| `.discard(x)`                       |      |      | ✓   |       |        |\n",
    "| `.sort()`                           | ✓    |      |     |       |        |\n",
    "| `.reverse()`                        | ✓    |      |     |       |        |\n",
    "| `.setdefault(k, v)`                 |      | ✓    |     |       |        |\n",
    "| `.clear()`                          | ✓    | ✓    | ✓   |       |        |\n",
    "| `.intersection_update(t)`           |      |      | ✓   |       |        |\n",
    "| `.difference_update(t)`             |      |      | ✓   |       |        |\n",
    "| `.symmetric_difference_update(t)`   |      |      | ✓   |       |        |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5628e9e",
   "metadata": {},
   "source": [
    "### In-place Set Operations\n",
    "\n",
    "The algebra above creates new sets. The corresponding update methods change the existing set and return `None`. This return-value rule applies to these update methods; methods such as `pop()` mutate a collection and return a removed element.\n",
    "\n",
    "| New set | Change the original set |\n",
    "| --- | --- |\n",
    "| `a.union(b)` | `a.update(b)` |\n",
    "| `a.intersection(b)` | `a.intersection_update(b)` |\n",
    "| `a.difference(b)` | `a.difference_update(b)` |\n",
    "| `a.symmetric_difference(b)` | `a.symmetric_difference_update(b)` |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-030ea21c",
   "metadata": {},
   "source": [
    "```{index} in-place set operation, set.intersection_update(), set.difference_update()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "b5ec5d39",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.541103Z",
     "iopub.status.busy": "2026-10-13T02:30:20.541063Z",
     "iopub.status.idle": "2026-10-13T02:30:20.542678Z",
     "shell.execute_reply": "2026-10-13T02:30:20.542534Z"
    }
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "New union: [1, 2, 3, 4, 5]\n",
      "Original unchanged: [1, 2, 3]\n",
      "After update: [1, 2, 3, 4, 5]\n",
      "Update returned: None\n",
      "intersection_update: [3]\n",
      "difference_update: [1, 2]\n",
      "symmetric_difference_update: [1, 2, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "a = {1, 2, 3}\n",
    "b = {3, 4, 5}\n",
    "combined = a.union(b)\n",
    "print('New union:', sorted(combined))\n",
    "print('Original unchanged:', sorted(a))\n",
    "result = a.update(b)\n",
    "print('After update:', sorted(a))\n",
    "print('Update returned:', result)\n",
    "\n",
    "a = {1, 2, 3}\n",
    "a.intersection_update(b)\n",
    "print('intersection_update:', sorted(a))\n",
    "a = {1, 2, 3}\n",
    "a.difference_update(b)\n",
    "print('difference_update:', sorted(a))\n",
    "a = {1, 2, 3}\n",
    "a.symmetric_difference_update(b)\n",
    "print('symmetric_difference_update:', sorted(a))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02f8779f",
   "metadata": {},
   "source": [
    "### Adding elements:\n",
    "\n",
    "- `add()`\n",
    "- `update()`: adds multiple elements, similar to `dict.update()`. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0ce3c00",
   "metadata": {},
   "source": [
    "```{index} set.add(), set.update()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "5c7aafe4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.543338Z",
     "iopub.status.busy": "2026-10-13T02:30:20.543297Z",
     "iopub.status.idle": "2026-10-13T02:30:20.544808Z",
     "shell.execute_reply": "2026-10-13T02:30:20.544650Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5, 6}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = {1, 2, 3}\n",
    "s.add(4)            # {1, 2, 3, 4}\n",
    "s.update([5, 6])    # {1, 2, 3, 4, 5, 6}\n",
    "s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4898cd7e",
   "metadata": {},
   "source": [
    "### Copy vs aliasing\n",
    "\n",
    "Sets are mutable, so assignment shares the same object. Use `.copy()` when you need an independent set."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-4898cd7e",
   "metadata": {},
   "source": [
    "```{index} aliasing, set.copy()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "64de2dc2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.545594Z",
     "iopub.status.busy": "2026-10-13T02:30:20.545540Z",
     "iopub.status.idle": "2026-10-13T02:30:20.547045Z",
     "shell.execute_reply": "2026-10-13T02:30:20.546888Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: {1, 2, 3}\n",
      "b: {1, 2, 3}\n",
      "c: {1, 2}\n"
     ]
    }
   ],
   "source": [
    "a = {1, 2}\n",
    "b = a               # alias (same object)\n",
    "c = a.copy()        # separate object\n",
    "\n",
    "a.add(3)\n",
    "print(\"a:\", a)\n",
    "print(\"b:\", b)\n",
    "print(\"c:\", c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a7e4012",
   "metadata": {},
   "source": [
    "### Removing elements:\n",
    "\n",
    "- `remove()`\n",
    "- `discard()`\n",
    "- `pop()`\n",
    "- `clear()`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08d118f4",
   "metadata": {},
   "source": [
    "```{index} set.remove(), set.discard(), set.pop()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "32830bae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.547731Z",
     "iopub.status.busy": "2026-10-13T02:30:20.547689Z",
     "iopub.status.idle": "2026-10-13T02:30:20.549113Z",
     "shell.execute_reply": "2026-10-13T02:30:20.548958Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2}\n",
      "{1, 2}\n",
      "{2}\n",
      "set()\n"
     ]
    }
   ],
   "source": [
    "s = {1, 2, 3}\n",
    "\n",
    "s.remove(3)     # raises KeyError if not found\n",
    "print(s)        # {1, 2}\n",
    "\n",
    "s.discard(3)    # silent if not found — safer\n",
    "print(s)        # {1, 2}\n",
    "\n",
    "s.pop()         # removes and returns an arbitrary element\n",
    "print(s)        # which item is removed is arbitrary\n",
    "\n",
    "s.clear()       # empties the set\n",
    "print(s)        # set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43cdb10f",
   "metadata": {},
   "source": [
    "If you use `remove()` in a `for` loop for a set, you may run into an error because Python creates an internal iterator that tracks position inside the set. The moment you call `s.remove()`, the set's structure changes and the iterator breaks and raises an error.\n",
    "\n",
    "The solution to this problem is to iterate over a copy or just use a `while` loop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "8712a534",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.549773Z",
     "iopub.status.busy": "2026-10-13T02:30:20.549731Z",
     "iopub.status.idle": "2026-10-13T02:30:20.551356Z",
     "shell.execute_reply": "2026-10-13T02:30:20.551219Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing 1\n"
     ]
    },
    {
     "ename": "RuntimeError",
     "evalue": "Set changed size during iteration",
     "output_type": "error",
     "traceback": [
      "\u001b[31mRuntimeError\u001b[39m\u001b[31m:\u001b[39m Set changed size during iteration\n"
     ]
    }
   ],
   "source": [
    "%%expect RuntimeError\n",
    "s = {1, 2, 3,}\n",
    "for item in s:\n",
    "    s.remove(item)\n",
    "    print(f\"Processing {item}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "074240f6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.552021Z",
     "iopub.status.busy": "2026-10-13T02:30:20.551980Z",
     "iopub.status.idle": "2026-10-13T02:30:20.553552Z",
     "shell.execute_reply": "2026-10-13T02:30:20.553418Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing 2\n",
      "Processing 3\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "set()"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### iterate through copy of the set while modifying the original\n",
    "\n",
    "for item in s.copy():   # iterate over copy\n",
    "    s.remove(item)      # modify original safely\n",
    "    print(f\"Processing {item}\")\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "ce404de4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.554210Z",
     "iopub.status.busy": "2026-10-13T02:30:20.554169Z",
     "iopub.status.idle": "2026-10-13T02:30:20.555449Z",
     "shell.execute_reply": "2026-10-13T02:30:20.555296Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing 1\n",
      "Processing 2\n",
      "Processing 3\n"
     ]
    }
   ],
   "source": [
    "# process all items, consuming the set\n",
    "\n",
    "s = {1, 2, 3}\n",
    "while s:\n",
    "    item = s.pop()\n",
    "    print(f\"Processing {item}\")\n",
    "# s is now empty"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8929f271",
   "metadata": {},
   "source": [
    "`s.pop()` is useful when you want to process and consume a set one element at a time, and you don't care which element you get. This behavior is different from `pop()` in `list` and `dict`.\n",
    "\n",
    "| | `list.pop()` | `dict.pop()` | `set.pop()` |\n",
    "|---|---|---|---|\n",
    "| **Removes** | by index | by key | arbitrary element |\n",
    "| **Returns** | removed value | removed value | removed value |\n",
    "| **Default arg** | index (default `-1`) | key + optional default | none |\n",
    "| **If not found** | `IndexError` | `KeyError` (or default) | `KeyError` |\n",
    "| **Predictable?** | yes (by index) | yes (by key) | no (arbitrary item) |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5e935c7",
   "metadata": {},
   "source": [
    "### Checking membership:\n",
    "\n",
    "The `in` and `not in` operators test whether a value is in a set. Because sets are built on hashing, this check stays fast even for very large sets."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9611a6e",
   "metadata": {},
   "source": [
    "```{index} membership testing; set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "d26aa7e7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.556117Z",
     "iopub.status.busy": "2026-10-13T02:30:20.556077Z",
     "iopub.status.idle": "2026-10-13T02:30:20.557312Z",
     "shell.execute_reply": "2026-10-13T02:30:20.557176Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "s = {1, 2, 3}\n",
    "\n",
    "print(3 in s)         # True\n",
    "print(3 not in s)     # False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f97d7ed3",
   "metadata": {},
   "source": [
    "### Subset & Superset:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e9e1d38",
   "metadata": {},
   "source": [
    "```{index} subset, superset, issubset(), issuperset()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "fa4c9d3d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.558008Z",
     "iopub.status.busy": "2026-10-13T02:30:20.557966Z",
     "iopub.status.idle": "2026-10-13T02:30:20.559529Z",
     "shell.execute_reply": "2026-10-13T02:30:20.559391Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {1, 2}\n",
    "b = {1, 2, 3}\n",
    "\n",
    "a.issubset(b)    # True — all of a is in b\n",
    "b.issuperset(a)  # True — b contains all of a\n",
    "a.isdisjoint(b)  # False — they share elements"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8576fdd",
   "metadata": {},
   "source": [
    "Operator equivalents for subset/superset are often used in real code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "1165718f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.560183Z",
     "iopub.status.busy": "2026-10-13T02:30:20.560142Z",
     "iopub.status.idle": "2026-10-13T02:30:20.561505Z",
     "shell.execute_reply": "2026-10-13T02:30:20.561379Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "a = {1, 2}\n",
    "b = {1, 2, 3}\n",
    "\n",
    "print(a < b)    # proper subset\n",
    "print(a <= b)   # subset\n",
    "print(b > a)    # proper superset\n",
    "print(b >= a)   # superset\n",
    "print(a <= a)   # True (same set is subset of itself)\n",
    "print(a < a)    # False (not a proper subset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "6619fd2a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.562259Z",
     "iopub.status.busy": "2026-10-13T02:30:20.562205Z",
     "iopub.status.idle": "2026-10-13T02:30:20.563374Z",
     "shell.execute_reply": "2026-10-13T02:30:20.563245Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Update and Membership Check\n",
    "# 1. Start with fruits = {\"apple\", \"banana\"}.\n",
    "# 2. Add \"cherry\" and update with [\"banana\", \"mango\"].\n",
    "# 3. Remove \"apple\" safely.\n",
    "# 4. Print whether \"mango\" is in fruits.\n",
    "# 5. Print whether {\"banana\", \"cherry\"} is a subset of fruits.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "4b8d7159",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.564069Z",
     "iopub.status.busy": "2026-10-13T02:30:20.564029Z",
     "iopub.status.idle": "2026-10-13T02:30:20.565475Z",
     "shell.execute_reply": "2026-10-13T02:30:20.565337Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "fruits = {\"apple\", \"banana\"}\n",
    "fruits.add(\"cherry\")\n",
    "fruits.update([\"banana\", \"mango\"])\n",
    "fruits.discard(\"apple\")\n",
    "\n",
    "print(\"mango\" in fruits)\n",
    "print({\"banana\", \"cherry\"}.issubset(fruits))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4393f0dd",
   "metadata": {},
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c22d640",
   "metadata": {},
   "source": [
    "## Frozensets, Hashability, and Performance\n",
    "\n",
    "A frozenset is an immutable version of a set. Once created, elements cannot be added or removed. This is useful when, for example, you need to protect data from modification, to use set as dict key or set element, or for graph edges and combinations."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-7c22d640",
   "metadata": {},
   "source": [
    "```{index} frozenset, immutable set\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "8e7afb6d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.566115Z",
     "iopub.status.busy": "2026-10-13T02:30:20.566072Z",
     "iopub.status.idle": "2026-10-13T02:30:20.567552Z",
     "shell.execute_reply": "2026-10-13T02:30:20.567424Z"
    }
   },
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'frozenset' object has no attribute 'add'",
     "output_type": "error",
     "traceback": [
      "\u001b[31mAttributeError\u001b[39m\u001b[31m:\u001b[39m 'frozenset' object has no attribute 'add'\n"
     ]
    }
   ],
   "source": [
    "%%expect AttributeError\n",
    "fs = frozenset({1, 2, 3})\n",
    "fs.add(4)     # AttributeError — frozensets are immutable\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56fa6e87",
   "metadata": {},
   "source": [
    "### Creating a frozenset\n",
    "\n",
    "The syntax for creating a frozenset is:\n",
    "\n",
    "```python\n",
    "frozenset()            # empty frozenset\n",
    "frozenset(iterable)    # from any iterable (list, set, string, etc.)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b0a4035",
   "metadata": {},
   "source": [
    "```{index} frozenset\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "9e545a44",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.568280Z",
     "iopub.status.busy": "2026-10-13T02:30:20.568239Z",
     "iopub.status.idle": "2026-10-13T02:30:20.569552Z",
     "shell.execute_reply": "2026-10-13T02:30:20.569397Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "frozenset({1, 2, 3})\n",
      "frozenset({'e', 'l', 'o', 'h'})\n"
     ]
    }
   ],
   "source": [
    "fs = frozenset([1, 2, 3])\n",
    "print(fs)                   # frozenset({1, 2, 3})\n",
    "fs = frozenset(\"hello\")\n",
    "print(fs)                   # element order may vary"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "765dd1ec",
   "metadata": {},
   "source": [
    "### Why use a frozenset?\n",
    "\n",
    "A frozenset is immutable and contains only hashable elements. It is itself hashable, so it can be: \n",
    "\n",
    "- used as a dictionary key, or \n",
    "- stored inside another set."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-765dd1ec",
   "metadata": {},
   "source": [
    "```{index} frozenset as dict key, set of sets\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "c1f80041",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.570200Z",
     "iopub.status.busy": "2026-10-13T02:30:20.570158Z",
     "iopub.status.idle": "2026-10-13T02:30:20.571362Z",
     "shell.execute_reply": "2026-10-13T02:30:20.571203Z"
    }
   },
   "outputs": [],
   "source": [
    "# As a dict key\n",
    "d = {frozenset({1, 2}): \"pair\"}\n",
    "\n",
    "# Inside a set\n",
    "s = {frozenset({1, 2}), frozenset({3, 4})}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f91f361e",
   "metadata": {},
   "source": [
    "| Feature          | set               | frozenset              |\n",
    "|------------------|-------------------|------------------------|\n",
    "| Mutable          | Yes               | No                     |\n",
    "| Hashable         | No                | Yes                    |\n",
    "| Can be dict key  | No                | Yes                    |\n",
    "| Set operations   | All               | Non-mutating only      |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ebc4e8a",
   "metadata": {},
   "source": [
    "### Set Performance and Membership"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df17d856",
   "metadata": {},
   "source": [
    "```{index} hash table; set, O(1) lookup\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0350b947",
   "metadata": {},
   "source": [
    "When you store a key in a dictionary or an element in a set, Python calls hash() on it to compute an integer, then uses that integer to determine where to store the value in memory. This is called a **hash table**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b918d6d",
   "metadata": {},
   "source": [
    "The benefit is that lookups are usually O(1) on average: Python jumps directly to a bucket via hash instead of scanning the whole collection. In the worst case (many collisions), lookup can degrade toward O(n)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "28e6d5f5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.572049Z",
     "iopub.status.busy": "2026-10-13T02:30:20.572009Z",
     "iopub.status.idle": "2026-10-13T02:30:20.573290Z",
     "shell.execute_reply": "2026-10-13T02:30:20.573134Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "# A missing target forces a list to check every element.\n",
    "print('pear' in ['apple', 'banana', 'cherry'])\n",
    "# A set uses hashing for average O(1) membership.\n",
    "print('pear' in {'apple', 'banana', 'cherry'})\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeb39265",
   "metadata": {},
   "source": [
    "(set-bigo)=\n",
    "**O(n)** and **O(1)** come from **Big O notation**, which describes how the **speed** of an operation scales with the **size** of the data. The full treatment of Big O comes in the Algorithms chapter, where sorting and searching will be covered.\n",
    "\n",
    "For now, just know that:\n",
    "- **Average O(1)**: hash-table lookups in `dict`/`set` are constant time on average, because Python uses the hash to jump to a bucket.\n",
    "- **Worst-case O(n)**: if many keys collide into the same bucket, Python may need to scan multiple entries.\n",
    "- **O(n)**: **linear time**. The operation gets slower as the collection grows. A list search is O(n) because Python checks each element one by one until it finds a match:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "4caa242e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.573915Z",
     "iopub.status.busy": "2026-10-13T02:30:20.573876Z",
     "iopub.status.idle": "2026-10-13T02:30:20.575175Z",
     "shell.execute_reply": "2026-10-13T02:30:20.575032Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "d = {'apple': 1, 'banana': 2, 'cherry': 3}\n",
    "print(d['apple'])  # Average O(1) lookup; elapsed time need not be identical at every size.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "7baa8ed3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.575830Z",
     "iopub.status.busy": "2026-10-13T02:30:20.575791Z",
     "iopub.status.idle": "2026-10-13T02:30:20.577181Z",
     "shell.execute_reply": "2026-10-13T02:30:20.577057Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"apple\" in [\"apple\", \"banana\", \"cherry\"]  # checks up to n items"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa00c97b",
   "metadata": {},
   "source": [
    "Big O describes growth in work, not an exact duration. Hashing and equality checks also have costs, so the comparison below uses simple integer keys to focus on collection size.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e512f70",
   "metadata": {},
   "source": [
    "You already saw this in the **dictionary** section, and the same idea applies here:\n",
    "\n",
    "- **O(1)** means near-constant lookup time on average (`key in dict`, `item in set`).\n",
    "- **O(n)** means linear time, where Python may scan through many elements (`item in list`).\n",
    "\n",
    "So for membership checks, sets are usually much faster than lists as data grows."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17fe185d",
   "metadata": {},
   "source": [
    "### Measure Growth and Construction Cost\n",
    "\n",
    "Section 7.3 compared repeated list and dictionary lookups. Add sets to that comparison at several sizes. The missing target makes the list scan all entries. Each reported lookup time is the best of three batches, divided by the number of repetitions.\n",
    "\n",
    "Build the lookup collections outside the lookup timing, then measure construction separately. These measurements illustrate a tradeoff: a set takes work to build, but can be reused across many searches. Timings vary by machine and do not prove a complexity bound.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c36e22e6",
   "metadata": {},
   "source": [
    "```{index} constant time (O(1)), timeit.repeat(), set construction cost\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "ad5e500f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.577868Z",
     "iopub.status.busy": "2026-10-13T02:30:20.577816Z",
     "iopub.status.idle": "2026-10-13T02:30:20.710898Z",
     "shell.execute_reply": "2026-10-13T02:30:20.710688Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Size    list us    dict us     set us    build set us\n",
      "  100      0.340      0.016      0.017           0.677\n",
      " 1000      3.304      0.019      0.017           4.730\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10000     33.947      0.016      0.016          48.846\n"
     ]
    }
   ],
   "source": [
    "from timeit import repeat\n",
    "\n",
    "print('Size    list us    dict us     set us    build set us')\n",
    "for n in (100, 1_000, 10_000):\n",
    "    values = list(range(n))\n",
    "    lookup = dict.fromkeys(values)\n",
    "    members = set(values)\n",
    "    target = -1\n",
    "    repetitions = 1_000\n",
    "    def per_lookup(collection):\n",
    "        seconds = min(repeat(lambda: target in collection, number=repetitions, repeat=3))\n",
    "        return seconds / repetitions * 1e6\n",
    "    build_seconds = min(repeat(lambda: set(values), number=100, repeat=3)) / 100\n",
    "    print(f'{n:5d} {per_lookup(values):10.3f} {per_lookup(lookup):10.3f} '\n",
    "          f'{per_lookup(members):10.3f} {build_seconds * 1e6:15.3f}')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ccad537",
   "metadata": {},
   "source": [
    "### Choose a Set or a Dictionary for Word Lookup\n",
    "\n",
    "```{index} membership testing; set, dictionary design\n",
    "```\n",
    "\n",
    "For a reverse-word search, membership alone is enough: a set stores which words exist. A dictionary is useful when each word must also map to information such as its frequency. Build either lookup once and reuse it. The loop below examines each distinct word once; its output is a list of directed matches, so both directions of a pair appear.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "f254b367",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.711787Z",
     "iopub.status.busy": "2026-10-13T02:30:20.711722Z",
     "iopub.status.idle": "2026-10-13T02:30:20.713671Z",
     "shell.execute_reply": "2026-10-13T02:30:20.713477Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reverse matches: [('cat', 'tac'), ('desserts', 'stressed'), ('stressed', 'desserts'), ('tac', 'cat')]\n",
      "cat exists: True\n",
      "cat frequency: 2\n"
     ]
    }
   ],
   "source": [
    "words = ['stressed', 'desserts', 'cat', 'tac', 'python', 'cat']\n",
    "word_set = set(words)\n",
    "matches = [(word, word[::-1]) for word in sorted(word_set) if word[::-1] in word_set]\n",
    "print('Reverse matches:', matches)\n",
    "\n",
    "from collections import Counter\n",
    "word_counts = Counter(words)\n",
    "print('cat exists:', 'cat' in word_set)\n",
    "print('cat frequency:', word_counts['cat'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "6993e124",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.714446Z",
     "iopub.status.busy": "2026-10-13T02:30:20.714390Z",
     "iopub.status.idle": "2026-10-13T02:30:20.715639Z",
     "shell.execute_reply": "2026-10-13T02:30:20.715477Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Choose List or Set *(applied)*\n",
    "# For each task, choose list or set and create the data structure.\n",
    "# 1. Keep every score in order, including duplicates: 88, 92, 88, 75.\n",
    "# 2. Keep only the unique tags from: \"python\", \"data\", \"python\", \"text\".\n",
    "# 3. Check whether \"data\" appears in the tags.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "a160f642",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.716439Z",
     "iopub.status.busy": "2026-10-13T02:30:20.716387Z",
     "iopub.status.idle": "2026-10-13T02:30:20.718476Z",
     "shell.execute_reply": "2026-10-13T02:30:20.718023Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[88, 92, 88, 75]\n",
      "{'python', 'text', 'data'}\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "scores = [88, 92, 88, 75]\n",
    "tags = {\"python\", \"data\", \"python\", \"text\"}\n",
    "print(scores)\n",
    "print(tags)\n",
    "print(\"data\" in tags)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df369e30",
   "metadata": {},
   "source": [
    "### Set Comprehensions\n",
    "\n",
    "A **set comprehension** builds a set from an expression, using the same syntax as a list comprehension but with curly braces `{}`. Because the result is a set, duplicates are automatically discarded.\n",
    "\n",
    "The syntax for creating sets is:\n",
    "\n",
    "```python\n",
    "{expression for item in iterable}\n",
    "{expression for item in iterable if condition}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa1d126b",
   "metadata": {},
   "source": [
    "```{index} set comprehension\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "d2c4b705",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.719748Z",
     "iopub.status.busy": "2026-10-13T02:30:20.719640Z",
     "iopub.status.idle": "2026-10-13T02:30:20.721819Z",
     "shell.execute_reply": "2026-10-13T02:30:20.721609Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Square set: {0, 9, 4, 1}\n",
      "Unique word lengths: {3, 4, 5}\n",
      "Vowels found: {'e', 'o'}\n"
     ]
    }
   ],
   "source": [
    "# Create a set of squares\n",
    "square_set = {x**2 for x in range(-3, 4)}\n",
    "print(\"Square set:\", square_set)\n",
    "\n",
    "# Remove duplicates and transform\n",
    "sentence = \"the quick brown fox jumps over the lazy dog\"\n",
    "unique_lengths = {len(word) for word in sentence.split()}\n",
    "print(\"Unique word lengths:\", unique_lengths)\n",
    "\n",
    "# Filter vowels\n",
    "vowels = {char.lower() for char in \"Hello World\" if char.lower() in 'aeiou'}\n",
    "print(\"Vowels found:\", vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "eb832ca4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.722750Z",
     "iopub.status.busy": "2026-10-13T02:30:20.722685Z",
     "iopub.status.idle": "2026-10-13T02:30:20.724007Z",
     "shell.execute_reply": "2026-10-13T02:30:20.723813Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Set Comprehension Practice\n",
    "# 1. From nums = [1, 2, 2, 3, 4, 4, 5], build a set of squared values.\n",
    "# 2. From text = \"apple banana apple cherry\", build a set of unique word lengths.\n",
    "# 3. Print both sets.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "8f4a54d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.724715Z",
     "iopub.status.busy": "2026-10-13T02:30:20.724664Z",
     "iopub.status.idle": "2026-10-13T02:30:20.726240Z",
     "shell.execute_reply": "2026-10-13T02:30:20.726064Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Squares: {1, 4, 9, 16, 25}\n",
      "Unique lengths: {5, 6}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "nums = [1, 2, 2, 3, 4, 4, 5]\n",
    "squares = {n**2 for n in nums}\n",
    "\n",
    "text = \"apple banana apple cherry\"\n",
    "lengths = {len(word) for word in text.split()}\n",
    "\n",
    "print(\"Squares:\", squares)\n",
    "print(\"Unique lengths:\", lengths)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14fc1ba9",
   "metadata": {},
   "source": [
    "### Comparing with `dict` Comprehension\n",
    "\n",
    "Set and dictionary comprehensions both use curly braces, so they are easy to confuse. The difference is the colon: `{expr for ...}` builds a set, and `{key: value for ...}` builds a dictionary."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-14fc1ba9",
   "metadata": {},
   "source": [
    "```{index} dictionary comprehension, set comprehension\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "26bae0c1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:30:20.726992Z",
     "iopub.status.busy": "2026-10-13T02:30:20.726932Z",
     "iopub.status.idle": "2026-10-13T02:30:20.728818Z",
     "shell.execute_reply": "2026-10-13T02:30:20.728621Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Set comprehension — curly braces, no colon\n",
    "{x**2 for x in range(5)}\n",
    "\n",
    "# Dict comprehension — curly braces WITH colon\n",
    "{x: x**2 for x in range(5)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fc75f84",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
