{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c851b30b",
   "metadata": {},
   "source": [
    "# Built-in Types\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "590280af-b854-4853-92fe-5074a20ef059",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# Find project root by looking for _config.yml\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "# Add project root to path\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "# Import shared teaching helpers and cell magics\n",
    "from shared import thinkpython, diagram, jupyturtle, structshape\n",
    "from shared.download import download\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ee7e6f3-71c2-4a1a-a9fe-ed0999efa77a",
   "metadata": {},
   "source": [
    "A **type** describes what kind of **value** an **object** has and what operations make sense for it. The basic data types discussed here are **built-in types** that come with Python. When you design your own **classes**, you will be designing **your own types**. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebf1172c-ded1-47b6-a551-bd11bf7a3cf7",
   "metadata": {},
   "source": [
    "Python is **dynamically** typed, which means you don't have to declare the data type when creating a variable. The interpreter will figure it out at run time. For example, the variable `x` below will receive proper types without user intervention. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "35a77d8e-2fca-45cb-a41e-1424ce697122",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 10                ### int\n",
    "x = 10.0              ### float\n",
    "x = \"hello\"           ### str\n",
    "x = [1, 2, 3, ]       ### list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dea182d-390e-44af-95f5-9f1cdd33b9f3",
   "metadata": {},
   "source": [
    "## Python Built-in Types \n",
    "\n",
    "Python has **[standard types](https://docs.python.org/3/library/stdtypes.html)** built into the interpreter. The principal built-in types are: numerics, sequences, mappings, classes, instances, and exceptions. These built-in types are shipped with Python and are readily available to be used. New/custom types are created through designing new classes.\n",
    "\n",
    "The commonly used data types can be organized as table below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-0dea182d-390e-44af-9",
   "metadata": {},
   "source": [
    "```{index} built-in type\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d825d8d5-9855-4997-9c4d-d313bbf51532",
   "metadata": {},
   "source": [
    "```{figure} ../../figures/python-data-types.svg\n",
    "---\n",
    "width: 90%\n",
    "name: python-data-types\n",
    "---\n",
    "Python built-in data types. Adapted from a diagram in [a Codecademy article](https://www.codecademy.com/article/what-are-python-data-types-and-how-to-check-them).\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b309238b-55fa-437c-92e0-545b4aa1b959",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "The following table shows that:\n",
    "1. The built-in types can be grouped into **literal** and **collection** types.\n",
    "2. The text (`str`) type is listed as a special sequence type, whereas other sequence types are data collections.\n",
    "3. Boolean (`bool`) type is a subclass of the integer (`int`) type.\n",
    "\n",
    "| Group      | No.| Category      | Types                              | Remarks                                           | Sample Use Case |\n",
    "|------------|----|---------------|------------------------------------|---------------------------------------------------|------------------|\n",
    "| Literals   | 1  | Numeric       | `int`, `float`, `complex`          | Numbers for mathematical operations               | Counts, indices, ages, prices, measurements |\n",
    "|            | 2  | Text **sequence** | `str`                              | Text and character data                           | Names, messages, file paths |\n",
    "|            | 3  | Boolean       | `bool`                             | Logical values (True/False)                       | Flags, conditions, toggle states |\n",
    "|            | 4  | **Null**          | `NoneType`                         | Represents absence of value                       | Absence of value, default state |\n",
    "| Collections| 5  | Sequence      | **`list`**, **`tuple`**, **`range`**           | **Ordered collections** of items                  | Shopping cart items, student grades, coordinates, RGB colors |\n",
    "|            | 6  | Binary        | `bytes`, `bytearray`, `memoryview` | Binary data and memory manipulation               | Image data, encrypted content |\n",
    "|            | 7  | Set           | `set`, `frozenset`                 | Unordered collections of unique items         | Removing duplicates, membership testing |\n",
    "|            | 8  | Mapping       | **`dict`**                             | **Key-value** pairs                               | User profiles, configuration settings |\n",
    "\n",
    "\n",
    "*Note that the [standard type hierarchy](https://docs.python.org/3.14/reference/datamodel.html#the-standard-type-hierarchy) in the [Python Language Reference](https://docs.python.org/3.14/reference/index.html) lists 8 different built-in data types with a slightly different categorization"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09a1abc4-65a7-4b18-aee3-5035894b3346",
   "metadata": {},
   "source": [
    "## Type Checking\n",
    "\n",
    "1. Use **`type()`** when you want to inspect exactly what kind of object you have.\n",
    "2. Use **`isinstance()`** when your code needs to accept a family of related types."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-09a1abc4-65a7-4b18-a",
   "metadata": {},
   "source": [
    "```{index} type checking, type(), isinstance()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "6559bdce-95e7-48d3-9e9c-d196f678dcaf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'int'>\n",
      "<class 'float'>\n",
      "<class 'bool'>\n",
      "<class 'str'>\n",
      "<class 'list'>\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "### type()\n",
    "\n",
    "a = type(1)\n",
    "b = type(2.0)\n",
    "c = type(1 == 1)\n",
    "d = type(\"\")     \n",
    "\n",
    "e = type([1, 2, 3])\n",
    "f = type({\"a\": 1, \"b\": 2})\n",
    "print(a, b, c, d, e, f, sep='\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "0bfe7d3c-4bbe-4af3-8ec9-43a3e2e3365b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### isinstance()\n",
    "\n",
    "x = 5\n",
    "isinstance(x, int)      # True\n",
    "isinstance(x, str)      # False\n",
    "isinstance(x, float)    # False\n",
    "\n",
    "x = 3.14\n",
    "isinstance(x, (int, float))   # True — passes if x matches ANY type in the tuple"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b16cfece-9ac7-400c-8bf0-13b0a72121e1",
   "metadata": {},
   "source": [
    "Note that a Boolean value (`True` or `False`) is also an integer (`int`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "a7d1bef2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'bool'>\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### bool is int\n",
    "\n",
    "print(type(True))\n",
    "print(isinstance(True, bool)) # True; True is a Boolean value\n",
    "print(isinstance(True, int))  # True; bool is a subclass of int in Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch02-typecheck-ex",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Check value types\n",
    "# The variables below describe one item in a fruit order.\n",
    "# 1. Use type() to print the type of each variable.\n",
    "# 2. Use isinstance() with the tuple (int, float) to print whether\n",
    "#    quantity, price, and name are numbers.\n",
    "name = \"banana\"\n",
    "quantity = 6\n",
    "price = 0.25\n",
    "in_stock = True\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch02-typecheck-ex-answer",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "<class 'str'>\n<class 'int'>\n<class 'float'>\n<class 'bool'>\nTrue\nTrue\nFalse\n"
    }
   ],
   "source": [
    "### Solution\n",
    "name = \"banana\"\n",
    "quantity = 6\n",
    "price = 0.25\n",
    "in_stock = True\n",
    "\n",
    "print(type(name))\n",
    "print(type(quantity))\n",
    "print(type(price))\n",
    "print(type(in_stock))\n",
    "\n",
    "print(isinstance(quantity, (int, float)))   # True\n",
    "print(isinstance(price, (int, float)))      # True\n",
    "print(isinstance(name, (int, float)))       # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf3f2c85-79d8-4f5f-bc88-465b4b78b1c0",
   "metadata": {},
   "source": [
    "## Type Conversion\n",
    "\n",
    "Type conversion is the general process of converting a value from one data type to another. There are two ways of type conversion to change type:\n",
    "*   Type **casting** (**explicit** conversion) is performed by the programmer (e.g., using `int(\"42\")`) using the **type constructors**.\n",
    "*   Type **coercion** (**implicit** conversion) is performed automatically by the Python interpreter (e.g., `3 + 4.5` results in `7.5`, where the integer `3` is coerced to a float to match the other operand)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-cf3f2c85-79d8-4f5f-b",
   "metadata": {},
   "source": [
    "```{index} type conversion\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cf06e0b-ed93-46de-9456-e69b15db18d2",
   "metadata": {},
   "source": [
    "### Type Casting\n",
    "\n",
    "Built-in Python **types** are also **constructor functions** that create a new object of a given type, called **type casting**. \n",
    "\n",
    "| Function  | Converts To              | Example                             | Explanation                                           |\n",
    "| --------- | ------------------------ | ----------------------------------- | ----------------------------------------------------- |\n",
    "| `int()`   | Integer                  | `int(\"10\") → 10`                    | Converts string \"10\" to integer 10                    |\n",
    "| `float()` | Floating-point number    | `float(\"3.14\") → 3.14`              | Converts string \"3.14\" to floating-point 3.14         |\n",
    "| `str()`   | String                   | `str(25) → \"25\"`                    | Converts integer 25 to string \"25\"                    |\n",
    "| `bool()`  | Boolean (`True`/`False`) | `bool(0) → False`, `bool(5) → True` | **0 converts to False**, **non-zero values convert to True**  |\n",
    "| `list()`  | List                     | `list(\"abc\") → ['a','b','c']`       | Converts **string into list of individual characters**    |\n",
    "| `tuple()` | Tuple                    | `tuple([1,2,3]) → (1,2,3)`          | Converts list to immutable tuple                      |\n",
    "| `set()`   | Set                      | `set([1,1,2]) → {1,2}`              | Converts **list to set**, removing duplicate values       |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-5cf06e0b-ed93-46de-9",
   "metadata": {},
   "source": [
    "```{index} type casting, constructor function, int()\n",
    "```"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "306d7439-cb7d-4e73-aecf-2c1673faa4c4",
   "metadata": {},
   "source": [
    "You use constructor functions to convert values explicitly when conversion is valid. For example, the types `int`, `float`, and `str` can be used as **constructor functions**, meaning you can call the type itself to create/convert a value. These are both **type keywords** and **built-in functions** you call to construct objects. For example:\n",
    "- `int` is the integer type and can also take a floating-point number and convert it to an integer (always rounding down).\n",
    "- `float` represents the floating-point type and can also be used to convert an integer to a floating-point value.\n",
    "- `str` can convert an integer or floating-point number to a string.\n",
    "\n",
    "\n",
    "**Type casting** (explicit conversion) operation is done by the programmer. Type casting is necessary in cases like, e.g., when you want a numeric input from a user. Since the value input from `input()` is always a string, you must **cast** it to an integer (or float) to use it as a number. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "d5a11bd9-deeb-45c3-a527-fae17b5f9346",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "3.0\n",
      "3\n",
      "12.6\n",
      "\n",
      "<class 'int'>\n",
      "<class 'float'>\n",
      "<class 'str'>\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "### type casting \n",
    "\n",
    "a = int(3.33)       ### turn 3.33 to int 3\n",
    "b = float(3)        ### turn int 3 to float 3.0\n",
    "c = str(3)          ### turn int 3 to str '3'\n",
    "d = float('12.6')   ### turn str into float\n",
    "\n",
    "print(a, b, c, d, sep='\\n')\n",
    "print()\n",
    "print(type(a), type(b), type(c), type(d), sep='\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "0627105b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15 int\n",
      "0.0825 float\n",
      "15 items str\n"
     ]
    }
   ],
   "source": [
    "text_count = \"15\"\n",
    "count = int(text_count)\n",
    "rate = float(\"0.0825\")\n",
    "message = str(count) + \" items\"\n",
    "\n",
    "print(count, type(count).__name__)\n",
    "print(rate, type(rate).__name__)\n",
    "print(message, type(message).__name__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a09f141e-42ee-45af-84be-b3a2addee737",
   "metadata": {},
   "source": [
    "### Type Coercion\n",
    "\n",
    "Python sometimes performs automatic conversion, called **coercion**, in mixed numeric expressions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-a09f141e-42ee-45af-8",
   "metadata": {},
   "source": [
    "```{index} type coercion, implicit conversion\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "bfc775f4-04d1-433a-8ae3-6248cd6f445a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.0\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "### type coercion\n",
    "\n",
    "a = 7             # int\n",
    "b = 3.0           # float\n",
    "c = a + b         # Python automatically converts 'a' to a float (7.0) before addition\n",
    "print(c)          # Output: 10.0\n",
    "print(type(c))    # Output: <class 'float'>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "998f82d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.5\n",
      "<class 'float'>\n",
      "float\n"
     ]
    }
   ],
   "source": [
    "result = 3 + 2.5\n",
    "print(result)\n",
    "print(type(result))\n",
    "print(type(result).__name__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "623d2486",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Convert input-like text\n",
    "# Convert the string values below, then compute the total cost.\n",
    "quantity_text = \"6\"\n",
    "price_text = \"4.25\"\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "623d2486-answer",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25.5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "quantity_text = \"6\"\n",
    "price_text = \"4.25\"\n",
    "\n",
    "quantity = int(quantity_text)\n",
    "price = float(price_text)\n",
    "total = quantity * price\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c1ecb11-ebcf-4494-a7bb-61396182d556",
   "metadata": {},
   "source": [
    "### Type Hinting\n",
    "\n",
    "\n",
    "Type hints document the types a programmer expects. Python does **not** enforce these hints at runtime by default, but editors and checkers can use them to catch mistakes earlier. So, type hinting, also called **type annotation**, lets you write the expected type next to a variable name. A type hint is a note for humans and development tools, as Python does not enforce it at runtime.\n",
    "\n",
    "To add type hints, you do **variable annotation**, in which you add the types after the variable names. So, instead of\n",
    "\n",
    "```python\n",
    "name = \"Alice\"\n",
    "age = 20\n",
    "height = 5.9\n",
    "is_active = True\n",
    "```\n",
    "\n",
    "You write:\n",
    "\n",
    "```python\n",
    "name: str = \"Alice\"\n",
    "age: int = 20\n",
    "height: float = 5.9\n",
    "is_active: bool = True\n",
    "```\n",
    "\n",
    "The annotation after the colon says what kind of value the variable is expected to hold. \n",
    "\n",
    "When defining functions, you can do type hinting by using **function annotation**, which is the same notation in function parameters and return values with **`->`**:\n",
    "\n",
    "```python\n",
    "def add(a: int, b: int) -> int:\n",
    "    return a + b\n",
    "```\n",
    "\n",
    "For now, remember two rules:\n",
    "\n",
    "- type hints improve **readability** and help tools catch mistakes early;\n",
    "- type hints do **not** convert values or stop the program at runtime.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-8c1ecb11-ebcf-4494-a",
   "metadata": {},
   "source": [
    "```{index} type hint, variable annotation\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c5edf6d-aff5-4852-97f0-f8b6078dc946",
   "metadata": {},
   "source": [
    "Examples of variable annotations of type hinting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "6cc1cc61-c5ff-4b23-984a-7474dc66946f",
   "metadata": {},
   "outputs": [],
   "source": [
    "name: str = \"Alice\"\n",
    "age: int = 30\n",
    "gpa: float = 3.8\n",
    "is_active: bool = True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96a45a8f-7612-4a2b-bf09-fbe28f0c3d57",
   "metadata": {},
   "source": [
    "Examples of funtional annotations of type hinting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "220eff23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Maya: 92.0\n"
     ]
    }
   ],
   "source": [
    "def format_score(name: str, score: float) -> str:\n",
    "    return f\"{name}: {score:.1f}\"\n",
    "\n",
    "print(format_score(\"Maya\", 92))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efd7cc0d",
   "metadata": {},
   "source": [
    "## Core Scalar Types\n",
    "\n",
    "The most common scalar types are `int`, `float`, `str`, `bool`, and `NoneType`.\n",
    "\n",
    "| Type | Example | Common use |\n",
    "|---|---|---|\n",
    "| `int` | `42` | counts, indexes, whole numbers |\n",
    "| `float` | `3.14` | measurements, averages, rates |\n",
    "| `str` | `\"Python\"` | text |\n",
    "| `bool` | `True` | conditions and flags |\n",
    "| `NoneType` | `None` | missing or not-yet-available value |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-efd7cc0d",
   "metadata": {},
   "source": [
    "```{index} scalar type, None\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a5e6ab3-8845-4937-94b8-88d3a6898781",
   "metadata": {},
   "source": [
    "To print the values and types of these types, we can use a `for` loop to make the example more succinct. \n",
    "\n",
    "*The `__name__` is a **dunder** (double under) and is a name attribute of any class. `type(value)` gives you `<class 'TYPE_NAME'>` while with `.__name__` you get just 'TYPE_NAME' such as 'int'. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "b26cf5e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42           int\n",
      "3.14         float\n",
      "'Python'     str\n",
      "False        bool\n",
      "None         NoneType\n"
     ]
    }
   ],
   "source": [
    "items = 42\n",
    "average = 3.14\n",
    "language = \"Python\"\n",
    "finished = False\n",
    "missing = None\n",
    "\n",
    "for value in [items, average, language, finished, missing]:\n",
    "    print(f\"{repr(value):12} {type(value).__name__}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11d8a761",
   "metadata": {},
   "source": [
    "### Strings\n",
    "\n",
    "Python represents sequences of letters as **strings**, because the letters are strung together like beads on a necklace. Strings are one of the most commonly used built-in types. Some features about strings in Python:\n",
    "\n",
    "- A string is a sequence of characters enclosed in quotes.\n",
    "- You can use single, double, or triple quotation marks to create a string; they are all legal.\n",
    "- Double quotes make it easy to write a string that contains an apostrophe, which is treated the same as single quotes in programming.\n",
    "- You can index and slice strings, but you cannot mutate them in place:\n",
    "- Immutable: Strings are **immutable sequences**. Once you create a string, you cannot change it, just like all immutable objects. So, to \"modify\" a string, you have to build a new string from old ones.\n",
    "- **Indexing** & slicing: Unlike other literal objects, strings are indexable and they use zero-based indexing and negative indexing, with which you can use `[start:stop:step]` for indexing and slicing. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-11d8a761",
   "metadata": {},
   "source": [
    "```{index} string, concatenation, escape sequence\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "799486bf-6857-4204-b338-28cf0aed6f10",
   "metadata": {},
   "source": [
    "#### String Creation\n",
    "\n",
    "Strings can be created using single or double quotes. You can also wrap double quotes around single quotes if you need to include a quote inside the string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "6e3f3670-5b53-4ca3-97fd-5f3e661f1c88",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "hello\n",
      "hello\n"
     ]
    }
   ],
   "source": [
    "s1 = 'hello'\n",
    "s2 = \"hello\"\n",
    "s3 = \"\"\"hello\"\"\"\n",
    "\n",
    "print(s1, s2, s3, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ccd11be-d785-4f13-9a99-f702491563fa",
   "metadata": {},
   "source": [
    "#### Concatenation\n",
    "\n",
    "The `+` operator works with strings; it joins two strings into a single string, a process known as **concatenation**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "d6b3e724-10ec-4596-bf8a-be9a62ef074c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Well, it's a small world.\""
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'Well, ' + \"it's a small \" + 'world.'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f356417-c022-4266-b444-4ccfb9e2c62f",
   "metadata": {},
   "source": [
    "The multiplication (`*`) operator also works with strings; it makes multiple copies of a string and concatenates them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "12474890-40fa-4407-90b5-fb07428e3eb2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hello! Hello! Hello! Hello! '"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'Hello! ' * 4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62445fd3-eff3-4efc-8889-7094edf126c4",
   "metadata": {},
   "source": [
    "#### `len()`\n",
    "\n",
    "Python provides a useful function called `len` that computes the length of a string. Notice that `len` counts the letters between the quotes, but not the quotes. In collection types, `len` counts the number of elements in the collection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "1cc16300-66c2-4842-8893-ad09972edf26",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "fruit = \"apple\"\n",
    "fruits = [\"apple\", \"banana\", \"cherry\"]    ### this is a list, elements are in []\n",
    "\n",
    "print(len(fruit))\n",
    "print(len(fruits))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f1494f8-5ad7-4054-afbf-ab609d8fe783",
   "metadata": {},
   "source": [
    "#### Quoation Marks & Escaping\n",
    "\n",
    "An escape sequence is a combination of a backslash `\\` with a special character/symbol to treat the special characters as regular strings. \n",
    "\n",
    "Observe the following two strings. You see that we are trying to honor the single quote in a pair of double quotes. For that, you can either:\n",
    "\n",
    "- **enclose** the single quotation mark inside the double quotation marks as in the first example, or enclose the double quote with single quotes like the 2nd. \n",
    "- use an **escape sequence**. Note that in s3, we have three single quotation marks, and we are able to produce the same results as the first example.\n",
    "- Starting from s4, we have a syntax error because the quotation marks are not properly closed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "c7a68825-a9d5-42d7-8dc2-eb3ddb9e71b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "It's a sunny day.\n",
      "It\"s a sunny day.\n",
      "It's a sunny day.\n"
     ]
    }
   ],
   "source": [
    "s1 = \"It's a sunny day.\"   ### double quote enclose single\n",
    "s2 = 'It\"s a sunny day.'   ### ... but legal\n",
    "s3 = 'It\\'s a sunny day.'  ### escape single quote\n",
    "\n",
    "print(s1, s2, s3, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "185a20f4-16b0-4112-8e9a-6b7d231415b2",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "unterminated string literal (detected at line 1) (3841685661.py, line 1)",
     "output_type": "error",
     "traceback": [
      "  \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[49]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m    \u001b[39m\u001b[31ms4 = 'It's a sunny day.'   ### illegal: not closed\u001b[39m\n                           ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m unterminated string literal (detected at line 1)\n"
     ]
    }
   ],
   "source": [
    "%%expect SyntaxError\n",
    "\n",
    "s4 = 'It's a sunny day.'   ### illegal: not closed\n",
    "s5 = \"It\"s a sunny day.\"   ### illegal: not closed\n",
    "print(s4, s5, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "315ca0c4-1315-4aa2-8e1d-2abc1f6ad159",
   "metadata": {},
   "source": [
    "Commonly used escape sequences are as follows.\n",
    "\n",
    "| Sequence | Meaning                                  |\n",
    "| -------- | ---------------------------------------- |\n",
    "| `\\'`     | Single quote inside single-quoted string |\n",
    "| `\\\"`     | Double quote inside double-quoted string |\n",
    "| `\\\\`     | Backslash literal                        |\n",
    "| `\\n`     | Newline                                  |\n",
    "| `\\t`     | Tab                                      |\n",
    "\n",
    "Some examples of escape sequences are:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "2d9c263c-199a-487f-9107-b895c6968209",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First line \n",
      " Second line\n",
      "Name:\tDoris\n",
      "He said \"Python is great!\"\n",
      "I'm learning Python\n"
     ]
    }
   ],
   "source": [
    "print(\"First line \\n Second line\")      ### \\n: gives new line (break)\n",
    "print(\"Name:\\tDoris\")                   ### \\t: tab\n",
    "print(\"He said \\\"Python is great!\\\"\")   ### print \" inside \"\"\n",
    "print('I\\'m learning Python')           ### show ' as a character, not quotation mark"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc4abb0c-e36a-45c9-9c13-db88db524ff8",
   "metadata": {},
   "source": [
    "#### Indexing and Slicing \n",
    "\n",
    "Strings are **sequences** of characters. You can access specific elements using **square bracket notation**. Python indexing starts at zero. Negative indexing in slicing starts at -1 from the end of the array.\n",
    "\n",
    "**Slice notation** allows you to grab parts of a string using the syntax of \\[`START`:`STOP`:`STEP`\\]. Use a **`colon`** to specify the start and stop indices. The **stop index is not included**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "ea6ec67c-9422-4865-8278-f729fdf52b25",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "h\n",
      "o\n",
      "o\n"
     ]
    }
   ],
   "source": [
    "s = 'hello'\n",
    "print(s[0])\n",
    "print(s[4])\n",
    "print(s[-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "1701defd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P\n",
      "n\n",
      "Pyt\n",
      "python\n"
     ]
    }
   ],
   "source": [
    "word = \"Python\"\n",
    "print(word[0])\n",
    "print(word[-1])\n",
    "print(word[0:3])\n",
    "print(word.lower())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7190c3fe-3495-4609-ae25-54c31a54898a",
   "metadata": {},
   "source": [
    "[Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace) (1815-1852) is considered the first computer programmer in the world."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "f317c937-03d5-4e9d-a873-639a0038c986",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ada Lovelace\n",
      "ADA LOVELACE\n",
      "A\n",
      "Ada\n",
      "Ada Lovelac\n"
     ]
    }
   ],
   "source": [
    "first = \"Ada\"\n",
    "last = \"Lovelace\"\n",
    "full_name = f\"{first} {last}\"\n",
    "print(full_name)\n",
    "print(full_name.upper())\n",
    "print(full_name[0])\n",
    "print(full_name[0:3])\n",
    "print(full_name[:-1])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "1d4c0aa8-a3fd-44b5-9c78-e28a21c099f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "applebananacherry\n",
      "apple\n",
      "banana\n",
      "cherry\n",
      "\n",
      "cherr\n"
     ]
    }
   ],
   "source": [
    "s = 'applebananacherry'\n",
    "print(s[0:])     ### applebananacherry\n",
    "print(s[:5])     ### apple\n",
    "print(s[5:11])   ### banana\n",
    "print(s[-6:])    ### cherry\n",
    "print(s[-6:0])   ### \n",
    "print(s[-6:-1])  ### cherr (stop exclusive)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "3f064d97",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Scalar types\n",
    "# Create one int, one float, one string, one Boolean, and one None value.\n",
    "# Print each value and its type name.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "3f064d97-answer",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3 int\n",
      "4.99 float\n",
      "Ada str\n",
      "True bool\n",
      "None NoneType\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "count = 3\n",
    "price = 4.99\n",
    "name = \"Ada\"\n",
    "active = True\n",
    "missing = None\n",
    "\n",
    "for value in [count, price, name, active, missing]:\n",
    "    print(value, type(value).__name__)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f62fb9a",
   "metadata": {},
   "source": [
    "## Collection Types\n",
    "\n",
    "Python’s [data structure](https://docs.python.org/3/tutorial/datastructures.html) are the built‑in **`container`** types you use to store, organize, and operate on groups of items/values. The four main data structure types are: `list`, `tuple`, `dictionary`, and `set`. \n",
    "\n",
    "The commonly used **built-in**/**standard** data structures can be grouped as: \n",
    "- Sequence Types\n",
    "- Set Types\n",
    "- Mapping Types\n",
    "\n",
    "```\n",
    "Collections (broad category)\n",
    "├── Sequence Types (ordered, indexed)\n",
    "│   ├── list\n",
    "│   ├── tuple\n",
    "│   ├── str (string)\n",
    "│   ├── range\n",
    "│   └── bytes/bytearray\n",
    "│\n",
    "├── Set Types (unordered, no duplicates)\n",
    "│   ├── set\n",
    "│   └── frozenset\n",
    "│\n",
    "└── Mapping Types (key-value pairs)\n",
    "    └── dict\n",
    "```\n",
    "\n",
    "Collections hold multiple values. This chapter only introduces the main collection types; later chapters develop them in depth.\n",
    "\n",
    "| Type | Literal form | Main idea | Mutable\n",
    "|---|---|---|--|\n",
    "| `list` | `[1, 2, 3]` | ordered, mutable sequence | Yes |\n",
    "| `tuple` | `(1, 2, 3)` | ordered, immutable sequence |No |\n",
    "| `dict` | `{\"name\": \"Ada\", \"age\": 17}` | key-value mapping | Yes |\n",
    "| `set` | `{1, 2, 3}` | unordered unique values | Yes |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-4f62fb9a",
   "metadata": {},
   "source": [
    "```{index} collection type, data structure\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d2573df-5afb-4ef5-88c2-62983d45a960",
   "metadata": {},
   "source": [
    "Among them, `list`, `tuple`, and `range` are [sequence types](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range). Also, `strings` are considered a sequence type (a kind of collection) because they behave like collections of characters, although conceptually, in many languages other than Python, strings are considered primitives, not collections.\n",
    "\n",
    "`range` is debatable as a “collection”; it’s really a lazy sequence generator, not a traditional data structure. It does look like a sequence, so Python treats it as one. Note that `range` stores a formula, not data; it computes values on demand. Therefore, `range` is a sequence protocol implementer, not a data container.\n",
    "\n",
    "A `set` object is an \"unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference\" [cite:p`Python Standard Library_2026`].\n",
    "\n",
    "Mapping in Python refers to data types that store **key-value** pairs, where each key is associated with a corresponding value. The most common mapping type is the dictionary (`dict`).\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "1f28beda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['apple', 'banana', 'apple', 'cherry']\n",
      "(3, 5)\n",
      "{'banana', 'cherry', 'apple'}\n",
      "{'name': 'Maya', 'score': 92}\n"
     ]
    }
   ],
   "source": [
    "### examples of the collection types\n",
    "\n",
    "fruit_list = [\"apple\", \"banana\", \"apple\", \"cherry\"]\n",
    "point_tuple = (3, 5)\n",
    "fruit_set = set(fruit_list)\n",
    "student_dict = {\"name\": \"Maya\", \"score\": 92}\n",
    "\n",
    "print(fruit_list)\n",
    "print(point_tuple)\n",
    "print(fruit_set)\n",
    "print(student_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06ed3562",
   "metadata": {},
   "source": [
    "### Lists (Ordered Collections)\n",
    "\n",
    "Lists store **multiple** items in **order** and are **mutable** (values can be changed after creation). `Lists`, just like `tuple` and `range`, are `sequences` of elements (similar to the array in many other languages) in **square brackets**, separated by _commas_. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-06ed3562",
   "metadata": {},
   "source": [
    "```{index} list, list.append()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "23554888-ef0f-446d-95de-cf6a48390da7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Numbers: [1, 2, 3, 4, 5]\n",
      "Fruits: ['Apple', 'Banana', 'Cherry']\n",
      "Mixed: [1, 'hello', 3.14, True]\n",
      "Empty list: []\n"
     ]
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "fruits = [\"Apple\", \"Banana\", \"Cherry\"]\n",
    "mixed = [1, \"hello\", 3.14, True]\n",
    "empty_list = []\n",
    "\n",
    "print(f\"Numbers: {numbers}\")\n",
    "print(f\"Fruits: {fruits}\")\n",
    "print(f\"Mixed: {mixed}\")\n",
    "print(f\"Empty list: {empty_list}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efec2552-8525-4c29-ba40-c91bfa1bf0e2",
   "metadata": {},
   "source": [
    "Common list operations:\n",
    "1. Append: `numbers.append(6)` → `[1, 2, 3, 4, 5, 6]`\n",
    "2. **Access/Indexing**: `numbers[0]` → `1`\n",
    "3. **Slicing**: `numbers[1:3]` → `[2, 3]`\n",
    "4. Length: `len(numbers)` → `5`\n",
    "5. Update: `numbers[0] = 99` → `[99, 2, 3, 4, 5, 6]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "6e256353-1608-4ab1-92a6-08b4bcc48bd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = ['a', 'b', 'c']\n",
    "\n",
    "my_list.append('d')\n",
    "my_list[0]\n",
    "my_list[1:3]\n",
    "len(my_list)\n",
    "my_list[0] = 'NEW'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "510aab89-0a2c-4795-b916-25a11e7853c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Original list: ['apple', 'banana', 'cherry']\n",
      "After append: ['apple', 'banana', 'cherry', 'date']\n",
      "First fruit: apple\n",
      "Number of fruits: 4\n"
     ]
    }
   ],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]        ### create a list by assignment\n",
    "print(f\"\\nOriginal list: {fruits}\")\n",
    "\n",
    "fruits.append(\"date\")                         ### mutable: update/change the list\n",
    "print(f\"After append: {fruits}\")\n",
    "\n",
    "print(f\"First fruit: {fruits[0]}\")            ### indexing\n",
    "print(f\"Number of fruits: {len(fruits)}\")     ### length"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "78e8b632-6673-4ed4-baba-0c5298575d32",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After modification: ['apple', 'banana', 'cranberry', 'date']\n"
     ]
    }
   ],
   "source": [
    "fruits[2] = \"cranberry\"                     ### lists are mutable: modify an element\n",
    "print(f\"After modification: {fruits}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87da82f0-6f97-4ab1-ab4f-788a92bbe6f1",
   "metadata": {},
   "source": [
    "Lists can contain any data type, including other lists (`nested`). You can access elements using **list indexing**. For nested lists, use chaining/stacking square brackets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4326b0e3-fe4b-4e80-8b89-f25973188cc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "lst = [1, 2, [3, 4]]\n",
    "lst[2][1]             ### 4\n",
    "\n",
    "nest = [1, 2, 3, [4, 5, ['target']]]\n",
    "nest[3][2][0]                         ### 'target'\n",
    "print(nest[3][2][0])                  ### target\n",
    "print(nest[3][2][0][0])               ### t (a list is a sequence)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76b101f2-4567-4dbc-8bdc-dd1801f02897",
   "metadata": {},
   "source": [
    "### Tuples (Immutable Sequences)\n",
    "\n",
    "Tuples are similar to lists, but they cannot be changed after creation (**immutable**). So, use tuples when you want to ensure data won't change:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-76b101f2-4567-4dbc-8",
   "metadata": {},
   "source": [
    "```{index} tuple, single-element tuple\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "b0b601d7-1c24-4ef8-8702-af1069ead176",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Converted to tuple: ('apple', 'banana', 'cranberry', 'date')\n",
      "first element in coordinate:  apple\n"
     ]
    }
   ],
   "source": [
    "fruits = tuple(fruits)\n",
    "print(f\"\\nConverted to tuple: {fruits}\")            ### ( )\n",
    "print(\"first element in coordinate: \", fruits[0])   ### indexing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "0a0790c8-77ae-4c85-8e64-62f03528a8b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "rgb_color = (255, 128, 0)\n",
    "single = (42,)             # Note the comma for single-item tuple"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8560a8b9-5bc0-4760-9b59-8e423a35a7ba",
   "metadata": {},
   "source": [
    "Since tuples are immutable, the following operation would generate an error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "cd4be18c-f43e-445a-88f2-c3ae67ebbd01",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[31mTypeError\u001b[39m\u001b[31m:\u001b[39m 'tuple' object does not support item assignment\n"
     ]
    }
   ],
   "source": [
    "%%expect TypeError\n",
    "fruits[2] = \"cherry\"  # This would cause an error because tuples are immutable!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "121ec32e-ad0b-4033-b8dd-5a3d127b95c9",
   "metadata": {},
   "source": [
    "### Mapping: `dictionary`\n",
    "\n",
    "In Python, a mapping type is a collection that stores data as `key–value` pairs, where each key is unique and maps to a corresponding value. The most common mapping type is the **`dictionary`** (`dict`), which allows flexible data organization and fast lookup, insertion, and modification of values by key rather than numerical index. An example of a Python dictionary: "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-121ec32e-ad0b-4033-b",
   "metadata": {},
   "source": [
    "```{index} dictionary, mapping, key-value pair\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "b4f15321-6ac0-4e57-947b-b8b8a6de6a6f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'Alice', 'age': 20, 'major': 'IST'}"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "student = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 20,\n",
    "    \"major\": \"IST\"\n",
    "}\n",
    "student"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f732d564-e0a7-48b1-8c40-e845fa5456e5",
   "metadata": {},
   "source": [
    "Common dictionary operations:\n",
    "- **Access**: `student[\"name\"]` → `\"Alice\"`\n",
    "- Add/Update: `student[\"gpa\"] = 3.8`\n",
    "- **Keys**: `student.keys()` → `dict_keys(['name', 'age', 'major'])`\n",
    "- **Values**: `student.values()` → `dict_values(['Alice', 20, 'Computer Science'])`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "5be1548c-4446-4028-b5de-df77fae82a27",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "student: {'name': 'Alice', 'age': 20, 'major': 'CS'}\n",
      "\n",
      "Student Name: Alice\n",
      "\n",
      "student: {'name': 'Alice', 'age': 20, 'major': 'IST', 'GPA': 3.5}\n",
      "\n",
      "dict_keys(['name', 'age', 'major', 'GPA'])\n",
      "dict_values(['Alice', 20, 'IST', 3.5])\n"
     ]
    }
   ],
   "source": [
    "student = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 20,\n",
    "    \"major\": \"CS\"\n",
    "}\n",
    "\n",
    "### the dict object \n",
    "print(f\"student: {student}\\n\")\n",
    "\n",
    "### access\n",
    "print(f\"Student Name: {student['name']}\\n\")   ### 1. access value by key\n",
    "\n",
    "### update\n",
    "student[\"major\"] = \"IST\"                     ### 2. update: MUTABLE\n",
    "student[\"GPA\"] = 3.5                        ### 2. add new key-value pair: MUTABLE\n",
    "\n",
    "### object after update\n",
    "print(f\"student: {student}\\n\")\n",
    "\n",
    "### keys and values\n",
    "print(student.keys())                       ### 3. keys\n",
    "print(student.values())                     ### 4. values\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f44fd25d-c947-4f48-8c44-91e8931e1cc2",
   "metadata": {},
   "source": [
    "### Sets\n",
    "\n",
    "A **set** is an unordered collection of unique elements. Sets are useful for removing duplicates and performing mathematical set operations.\n",
    "\n",
    "Key characteristics:\n",
    "- **Unordered**: Elements have no defined order\n",
    "- **Unique**: Automatically removes duplicate values\n",
    "- **Mutable**: Can add/remove elements\n",
    "- **No indexing**: Cannot access elements by position"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f44fd25d-c947-4f48-8",
   "metadata": {},
   "source": [
    "```{index} set, set operation\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "253062a0-78c6-4c9d-ada5-8385789353d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Set: {1, 2, 3, 4, 5}\n",
      "Unique values: {8, 9, 2, 5}\n",
      "From list: {24.1, 25.0, 23.5}\n"
     ]
    }
   ],
   "source": [
    "# Creating sets\n",
    "unique_numbers = {1, 2, 3, 4, 5}\n",
    "print(f\"Set: {unique_numbers}\")\n",
    "\n",
    "# Duplicates are automatically removed\n",
    "data = {5, 2, 8, 2, 5, 9}\n",
    "print(f\"Unique values: {data}\")\n",
    "\n",
    "# Creating from a list\n",
    "measurements = [23.5, 24.1, 23.5, 25.0]\n",
    "unique = set(measurements)\n",
    "print(f\"From list: {unique}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch02-sorted-md",
   "metadata": {},
   "source": [
    "Because a set has no order, Python may display its items in any order. When you need a predictable order, pass the set to the built-in `sorted()` function. It returns a new **list** with the items in ascending order (alphabetical for strings) and leaves the set unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch02-sorted-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['apple', 'banana', 'cherry']\n[1, 2, 3]\n"
    }
   ],
   "source": [
    "fruits = {\"cherry\", \"apple\", \"banana\", \"apple\"}\n",
    "print(sorted(fruits))       # ['apple', 'banana', 'cherry']\n",
    "print(sorted([3, 1, 2]))     # [1, 2, 3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "d4a75a3f-ca6e-4d34-86be-3d6d4cdbe4a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Union: {1, 2, 3, 4, 5}\n",
      "Intersection: {3}\n",
      "Difference: {1, 2}\n"
     ]
    }
   ],
   "source": [
    "# Basic set operations\n",
    "set_a = {1, 2, 3}\n",
    "set_b = {3, 4, 5}\n",
    "\n",
    "print(f\"Union: {set_a | set_b}\")          # All elements\n",
    "print(f\"Intersection: {set_a & set_b}\")   # Common elements\n",
    "print(f\"Difference: {set_a - set_b}\")     # In A but not B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "aa953c66",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Choose basic collections\n",
    "# 1. Store three city names in a list.\n",
    "# 2. Store one student's name and grade in a dictionary.\n",
    "# 3. Use a set to remove duplicate course codes.\n",
    "course_codes = [\"PY\", \"DS\", \"PY\", \"SQL\", \"DS\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "aa953c66-answer",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Rolla', 'Chicago', 'Boston']\n",
      "{'name': 'Maya', 'grade': 92}\n",
      "{'PY', 'DS', 'SQL'}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "cities = [\"Rolla\", \"Chicago\", \"Boston\"]\n",
    "student = {\"name\": \"Maya\", \"grade\": 92}\n",
    "course_codes = [\"PY\", \"DS\", \"PY\", \"SQL\", \"DS\"]\n",
    "unique_codes = set(course_codes)\n",
    "\n",
    "print(cities)\n",
    "print(student)\n",
    "print(unique_codes)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "442b7109-5c29-4e35-96eb-302a2f7667f4",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "2447fdd6-6ed3-4406-9fe6-ef8d4fd60206",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### Mutability\n",
    "\n",
    "Mutability and order are two important characteristics of Python data structures, summarized in the table below. \n",
    "\n",
    "\n",
    "| Type | Literal | `Mutable` | Ordered | Usage |\n",
    "|------|---------|---------|---------|-------|\n",
    "| **Sequence Types** | | | | |\n",
    "| list | `[1, 2, 3]` | **Yes** | Yes | General purpose; dynamic arrays; index/slice access. |\n",
    "| tuple | `(1, 2, 3)` | No | Yes | Fixed records; function returns; hashable if elements are.* |\n",
    "| range | `range(10)` | No | Yes | Memory-efficient integer sequences; iteration. |\n",
    "| str | `\"hi\"` | No | Yes | Text; immutable character sequences. |\n",
    "| **Set Types** | | | | |\n",
    "| set | `{1, 2, 3}` | **Yes** | No | Unique items; membership testing; set operations. |\n",
    "| frozenset | `frozenset({1,2})` | No | No | Immutable set; dict keys; set elements. |\n",
    "| **Mapping Types** | | | | |\n",
    "| dict | `{\"a\": 1, \"b\": 2}` | **Yes** | Yes** | Key-value lookups; counting; grouping; configuration. |\n",
    "\n",
    "**Notes:**\n",
    "- \\* Tuples are hashable only if all elements are hashable.\n",
    "- \\*\\* Dict ordering guaranteed in Python 3.7+.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-2447fdd6-6ed3-4406-9",
   "metadata": {},
   "source": [
    "```{index} mutability, ordered collection\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
