{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d61ec844",
   "metadata": {},
   "source": [
    "# Python Syntactic Sugar Cheatsheet\n",
    "\n",
    "A comprehensive reference for Python's most useful syntactic sugar patterns that make code more readable, efficient, and Pythonic.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28dfda1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Required imports for the code snippets in the notebook\n",
    "import re\n",
    "import time\n",
    "from contextlib import contextmanager"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc2dafc8",
   "metadata": {},
   "source": [
    "## 🟢 Essential Patterns (Everyone Should Know)\n",
    "\n",
    "### List Comprehensions\n",
    "\n",
    "**When to use:** Transform or filter a list of items\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "[expression for item in list]\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74e282fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Transform each number\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "squares = [x * x for x in numbers]\n",
    "print(f\"Squares: {squares}\")\n",
    "# Result: [1, 4, 9, 16, 25]\n",
    "\n",
    "# Filter with condition\n",
    "even_numbers = [x for x in numbers if x % 2 == 0]\n",
    "print(f\"Even numbers: {even_numbers}\")\n",
    "# Result: [2, 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d311a8a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Instead of this loop:\n",
    "result = []\n",
    "for x in numbers:\n",
    "    if x % 2 == 0:\n",
    "        result.append(x * x)\n",
    "\n",
    "print(f\"Loop result: {result}\")\n",
    "\n",
    "# Write this:\n",
    "result = [x * x for x in numbers if x % 2 == 0]\n",
    "print(f\"Comprehension result: {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b5d9a7d",
   "metadata": {},
   "source": [
    "### Dictionary Comprehensions\n",
    "\n",
    "**When to use:** Build dictionaries from existing data\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "{key: value for item in list}\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3bb2c75",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create word lengths dictionary\n",
    "words = [\"cat\", \"dog\", \"elephant\"]\n",
    "lengths = {word: len(word) for word in words}\n",
    "print(f\"Word lengths: {lengths}\")\n",
    "# Result: {'cat': 3, 'dog': 3, 'elephant': 8}\n",
    "\n",
    "# Transform values in existing dictionary\n",
    "prices = {\"apple\": 1.20, \"banana\": 0.80}\n",
    "rounded = {fruit: round(price) for fruit, price in prices.items()}\n",
    "print(f\"Rounded prices: {rounded}\")\n",
    "# Result: {'apple': 1, 'banana': 1}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eaeffdde",
   "metadata": {},
   "source": [
    "### F-strings (Python 3.6+)\n",
    "\n",
    "**When to use:** Insert variables into strings (better than `.format()` or `%`)\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "f\"Text {variable} more text\"\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98a9e7cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"Alice\"\n",
    "age = 25\n",
    "\n",
    "# Basic variable insertion\n",
    "message = f\"Hello {name}!\"\n",
    "print(message)\n",
    "# Result: \"Hello Alice!\"\n",
    "\n",
    "# Multiple variables\n",
    "info = f\"{name} is {age} years old\"\n",
    "print(info)\n",
    "# Result: \"Alice is 25 years old\"\n",
    "\n",
    "# Simple expressions\n",
    "status = f\"Adult: {age >= 18}\"\n",
    "print(status)\n",
    "# Result: \"Adult: True\"\n",
    "\n",
    "# Number formatting\n",
    "price = 19.99\n",
    "formatted = f\"Price: ${price:.2f}\"\n",
    "print(formatted)\n",
    "# Result: \"Price: $19.99\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64634fd2",
   "metadata": {},
   "source": [
    "### Basic Unpacking\n",
    "\n",
    "**When to use:** Get multiple values from lists/tuples at once\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c0eb6af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split coordinates\n",
    "point = [10, 20]\n",
    "x, y = point\n",
    "print(f\"x = {x}, y = {y}\")\n",
    "# x = 10, y = 20\n",
    "\n",
    "# Swap variables (no temp variable needed!)\n",
    "a, b = 5, 3\n",
    "print(f\"Before swap: a = {a}, b = {b}\")\n",
    "a, b = b, a  # Now a = 3, b = 5\n",
    "print(f\"After swap: a = {a}, b = {b}\")\n",
    "\n",
    "\n",
    "# Get function results\n",
    "def get_name_age():\n",
    "    return \"Alice\", 25\n",
    "\n",
    "\n",
    "name, age = get_name_age()\n",
    "print(f\"Name: {name}, Age: {age}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d59b59eb",
   "metadata": {},
   "source": [
    "### Basic zip() and enumerate()\n",
    "\n",
    "**When to use:** Combine lists or get index+value pairs\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4302fa6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# zip() - Combine lists:\n",
    "names = [\"Alice\", \"Bob\", \"Charlie\"]\n",
    "ages = [25, 30, 35]\n",
    "\n",
    "# Process pairs together\n",
    "print(\"Name-Age pairs:\")\n",
    "for name, age in zip(names, ages):\n",
    "    print(f\"{name}: {age}\")\n",
    "\n",
    "# Create dictionary from two lists\n",
    "people = dict(zip(names, ages))\n",
    "print(f\"People dictionary: {people}\")\n",
    "# Result: {'Alice': 25, 'Bob': 30, 'Charlie': 35}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91724695",
   "metadata": {},
   "outputs": [],
   "source": [
    "# enumerate() - Get index and value:\n",
    "items = [\"apple\", \"banana\", \"cherry\"]\n",
    "\n",
    "# Get position and item\n",
    "print(\"Items with index (starting from 0):\")\n",
    "for i, item in enumerate(items):\n",
    "    print(f\"{i}: {item}\")\n",
    "# Output: 0: apple, 1: banana, 2: cherry\n",
    "\n",
    "# Start counting from 1\n",
    "print(\"\\nItems with index (starting from 1):\")\n",
    "for i, item in enumerate(items, 1):\n",
    "    print(f\"{i}. {item}\")\n",
    "# Output: 1. apple, 2. banana, 3. cherry"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34e581e0",
   "metadata": {},
   "source": [
    "### Simple Conditional Expressions\n",
    "\n",
    "**When to use:** Choose between two values based on a condition\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "value_if_true if condition else value_if_false\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf4187eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "status = \"adult\" if age >= 18 else \"minor\"\n",
    "print(f\"Status: {status}\")\n",
    "\n",
    "# In lists\n",
    "numbers = [1, -2, 3, -4, 5]\n",
    "absolute = [x if x >= 0 else -x for x in numbers]\n",
    "print(f\"Absolute values: {absolute}\")\n",
    "# Result: [1, 2, 3, 4, 5]\n",
    "\n",
    "# Better than if/else for simple cases\n",
    "score = 75  # Example score\n",
    "grade = \"Pass\" if score >= 60 else \"Fail\"\n",
    "print(f\"Grade: {grade}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5daf5c21",
   "metadata": {},
   "source": [
    "## 🟡 Common Patterns (Useful in Most Projects)\n",
    "\n",
    "### Generator Expressions\n",
    "\n",
    "**When to use:** Process large amounts of data without storing everything in memory\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "(expression for item in list)\n",
    "```\n",
    "\n",
    "**Key Difference:** Uses `()` instead of `[]` - creates items one at a time\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae85be1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# For large data sets - saves memory\n",
    "large_numbers = range(1000000)\n",
    "\n",
    "# List comprehension - stores all million numbers\n",
    "# squares_list = [x * x for x in large_numbers]  # Uses lots of memory (commented to avoid memory issues)\n",
    "\n",
    "# Generator expression - creates one at a time\n",
    "squares_gen = (x * x for x in large_numbers)  # Uses little memory\n",
    "print(f\"Generator object: {squares_gen}\")\n",
    "\n",
    "# Use generators with functions that process items one by one\n",
    "total = sum(x * x for x in range(100))  # Using smaller range for demo\n",
    "print(f\"Sum of squares (0-99): {total}\")\n",
    "\n",
    "max_value = max(x * x for x in range(10))\n",
    "print(f\"Max square (0-9): {max_value}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5a73313",
   "metadata": {},
   "source": [
    "### Set Comprehensions\n",
    "\n",
    "**When to use:** Get unique values or remove duplicates while transforming\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "{expression for item in list}\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "727706eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get unique lengths\n",
    "words = [\"cat\", \"dog\", \"cat\", \"elephant\", \"dog\"]\n",
    "unique_lengths = {len(word) for word in words}\n",
    "print(f\"Unique lengths: {unique_lengths}\")\n",
    "# Result: {3, 8} - only unique values\n",
    "\n",
    "# Remove duplicates while transforming\n",
    "numbers = [1, 2, 2, 3, 3, 4]\n",
    "unique_squares = {x * x for x in numbers}\n",
    "print(f\"Unique squares: {unique_squares}\")\n",
    "# Result: {1, 4, 9, 16}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46b97363",
   "metadata": {},
   "source": [
    "### Advanced Unpacking with \\*\n",
    "\n",
    "**When to use:** Handle lists of unknown length or skip unwanted values\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f1a577b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get first, last, and everything in between\n",
    "scores = [95, 87, 92, 78, 88, 91]\n",
    "first, *middle, last = scores\n",
    "print(f\"First: {first}, Middle: {middle}, Last: {last}\")\n",
    "# first = 95, middle = [87, 92, 78, 88], last = 91\n",
    "\n",
    "# Skip values you don't need\n",
    "data = [\"header\", \"value1\", \"value2\", \"value3\", \"footer\"]\n",
    "header, *_, footer = data\n",
    "print(f\"Header: {header}, Footer: {footer}\")\n",
    "# header = 'header', footer = 'footer' (_ means \"ignore these\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbd5cecf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Function with flexible arguments\n",
    "def greet(name, *hobbies):\n",
    "    print(f\"Hi {name}!\")\n",
    "    if hobbies:\n",
    "        print(f\"I see you like: {', '.join(hobbies)}\")\n",
    "\n",
    "\n",
    "greet(\"Alice\", \"reading\", \"hiking\", \"coding\")\n",
    "\n",
    "# Unpack when calling functions\n",
    "coordinates = [10, 20, 30]\n",
    "print(\"Coordinates:\", *coordinates)  # Same as print(10, 20, 30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4bf9f5e",
   "metadata": {},
   "source": [
    "### The with Statement (Context Managers)\n",
    "\n",
    "**When to use:** Work with files, databases, or anything that needs cleanup\n",
    "\n",
    "**Why it's better:** Automatically handles closing/cleanup even if errors occur\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a21589d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a sample file for demonstration\n",
    "with open(\"/tmp/sample_data.txt\", \"w\") as f:\n",
    "    f.write(\"Hello, World!\\nThis is a sample file.\\nPython is awesome!\")\n",
    "\n",
    "# File handling - file automatically closes\n",
    "with open(\"/tmp/sample_data.txt\") as file:\n",
    "    content = file.read()\n",
    "    print(\"File content:\")\n",
    "    print(content)\n",
    "# File is guaranteed to be closed here, even if an error occurred"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "142196a4",
   "metadata": {},
   "source": [
    "### Walrus Operator := (Python 3.8+)\n",
    "\n",
    "**When to use:** Assign and use a value in the same line (avoid repeating expensive operations)\n",
    "\n",
    "**Basic Pattern:**\n",
    "\n",
    "```python\n",
    "if (variable := expression):\n",
    "    # use variable\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d42298ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Avoid calling expensive function twice\n",
    "def expensive_computation():\n",
    "    print(\"Computing...\")\n",
    "    return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n",
    "\n",
    "\n",
    "# Instead of calling twice:\n",
    "print(\"Bad approach (calls function twice):\")\n",
    "if len(expensive_computation()) > 10:\n",
    "    print(f\"Got {len(expensive_computation())} items\")  # Called twice!\n",
    "\n",
    "print(\"\\nGood approach (calls function once):\")\n",
    "# Write:\n",
    "if (n := len(expensive_computation())) > 10:\n",
    "    print(f\"Got {n} items\")  # Called only once"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85818303",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check and use in one line\n",
    "text = \"Phone: 123-456-7890\"\n",
    "if match := re.search(r\"\\d{3}-\\d{3}-\\d{4}\", text):\n",
    "    phone = match.group()\n",
    "    print(f\"Found phone: {phone}\")\n",
    "else:\n",
    "    print(\"No phone number found\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c837dda",
   "metadata": {},
   "source": [
    "### Slice Notation\n",
    "\n",
    "**When to use:** Get parts of lists, strings, or other sequences\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43de7fee",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "\n",
    "# Basic slicing\n",
    "first_three = data[:3]  # [0, 1, 2]\n",
    "last_three = data[-3:]  # [7, 8, 9]\n",
    "middle = data[2:7]  # [2, 3, 4, 5, 6]\n",
    "\n",
    "print(f\"First three: {first_three}\")\n",
    "print(f\"Last three: {last_three}\")\n",
    "print(f\"Middle: {middle}\")\n",
    "\n",
    "# Skip elements\n",
    "every_second = data[::2]  # [0, 2, 4, 6, 8]\n",
    "every_third = data[::3]  # [0, 3, 6, 9]\n",
    "\n",
    "print(f\"Every second: {every_second}\")\n",
    "print(f\"Every third: {every_third}\")\n",
    "\n",
    "# Reverse\n",
    "reversed_data = data[::-1]  # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n",
    "print(f\"Reversed: {reversed_data}\")\n",
    "\n",
    "# Remove first and last\n",
    "without_ends = data[1:-1]  # [1, 2, 3, 4, 5, 6, 7, 8]\n",
    "print(f\"Without ends: {without_ends}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c08f261",
   "metadata": {},
   "source": [
    "## 🔴 Advanced Patterns (Specialized Use Cases)\n",
    "\n",
    "### Pattern Matching (Python 3.10+)\n",
    "\n",
    "**When to use:** Complex conditional logic that's clearer than many if/elif statements\n",
    "\n",
    "**Why it's useful:** More readable than long if/elif chains, especially for structured data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37d528e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Instead of many if/elif statements\n",
    "def handle_user_data(data):\n",
    "    match data:\n",
    "        # Match exact values\n",
    "        case {\"status\": \"active\", \"role\": \"admin\"}:\n",
    "            return \"Admin user is active\"\n",
    "\n",
    "        # Match with variables (capture values)\n",
    "        case {\"status\": \"active\", \"role\": role}:\n",
    "            return f\"Active {role} user\"\n",
    "\n",
    "        # Match with conditions\n",
    "        case {\"age\": age} if age < 18:\n",
    "            return \"Minor user\"\n",
    "\n",
    "        # Match lists/tuples\n",
    "        case [first, *rest] if len(rest) > 5:\n",
    "            return f\"Long list starting with {first}\"\n",
    "\n",
    "        # Default case\n",
    "        case _:\n",
    "            return \"Unknown user type\"\n",
    "\n",
    "\n",
    "# Test the function\n",
    "test_cases = [\n",
    "    {\"status\": \"active\", \"role\": \"admin\"},\n",
    "    {\"status\": \"active\", \"role\": \"user\"},\n",
    "    {\"age\": 16},\n",
    "    [1, 2, 3, 4, 5, 6, 7, 8],\n",
    "    \"unknown\",\n",
    "]\n",
    "\n",
    "for test in test_cases:\n",
    "    result = handle_user_data(test)\n",
    "    print(f\"{test} -> {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d19ea6e",
   "metadata": {},
   "source": [
    "### Advanced Built-in Functions\n",
    "\n",
    "**Modern alternatives to older patterns:**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58386e16",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prefer comprehensions over map/filter\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "\n",
    "# Old style (still works, but less readable)\n",
    "squared_old = list(map(lambda x: x**2, numbers))\n",
    "evens_old = list(filter(lambda x: x % 2 == 0, numbers))\n",
    "\n",
    "# Modern style (preferred)\n",
    "squared_new = [x**2 for x in numbers]\n",
    "evens_new = [x for x in numbers if x % 2 == 0]\n",
    "\n",
    "print(f\"Old style - squared: {squared_old}\")\n",
    "print(f\"New style - squared: {squared_new}\")\n",
    "print(f\"Old style - evens: {evens_old}\")\n",
    "print(f\"New style - evens: {evens_new}\")\n",
    "\n",
    "# Complex example\n",
    "words = [\"hello\", \"world\", \"python\", \"is\", \"awesome\"]\n",
    "\n",
    "# Old style - hard to read\n",
    "result_old = list(map(str.upper, filter(lambda w: len(w) > 4, words)))\n",
    "\n",
    "# Modern style - clear and readable\n",
    "result_new = [word.upper() for word in words if len(word) > 4]\n",
    "\n",
    "print(f\"Old style result: {result_old}\")\n",
    "print(f\"New style result: {result_new}\")\n",
    "# Result: ['HELLO', 'WORLD', 'PYTHON', 'AWESOME']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85b404a4",
   "metadata": {},
   "source": [
    "### Custom Context Managers\n",
    "\n",
    "**When to use:** Create reusable patterns for setup/cleanup operations\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "660fee8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Simple custom context manager using a class:\n",
    "class Timer:\n",
    "    \"\"\"Context manager to time operations\"\"\"\n",
    "\n",
    "    def __enter__(self):\n",
    "        self.start = time.time()\n",
    "        return self\n",
    "\n",
    "    def __exit__(self, *args):\n",
    "        self.end = time.time()\n",
    "        print(f\"Operation took {self.end - self.start:.2f} seconds\")\n",
    "\n",
    "\n",
    "# Usage\n",
    "with Timer():\n",
    "    # Some operation\n",
    "    time.sleep(0.1)  # Simulate work\n",
    "    result = sum(range(100000))\n",
    "    print(f\"Calculated sum: {result}\")\n",
    "# Automatically prints timing when done"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7615324f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Using contextlib (simpler for basic cases)\n",
    "@contextmanager\n",
    "def temporary_setting(setting_name, temp_value):\n",
    "    \"\"\"Temporarily change a setting, then restore it\"\"\"\n",
    "\n",
    "    # Mock functions for demonstration\n",
    "    def get_setting(name):\n",
    "        return f\"old_{name}\"\n",
    "\n",
    "    def set_setting(name, value):\n",
    "        print(f\"Setting {name} to {value}\")\n",
    "\n",
    "    old_value = get_setting(setting_name)\n",
    "    set_setting(setting_name, temp_value)\n",
    "    try:\n",
    "        yield old_value\n",
    "    finally:\n",
    "        set_setting(setting_name, old_value)\n",
    "\n",
    "\n",
    "# Usage\n",
    "with temporary_setting(\"debug_mode\", True):\n",
    "    print(\"Debug mode is temporarily enabled\")\n",
    "    # Do some work here\n",
    "print(\"Debug mode automatically restored to previous value\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3170c51",
   "metadata": {},
   "source": [
    "## Common Mistakes to Avoid\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "023af12e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Generator Exhaustion\n",
    "print(\"=== Generator Exhaustion Demo ===\")\n",
    "# Problem: Generators can only be used once\n",
    "gen = (x * 2 for x in range(5))\n",
    "list1 = list(gen)  # [0, 2, 4, 6, 8]\n",
    "list2 = list(gen)  # [] - Empty! Generator is exhausted\n",
    "\n",
    "print(f\"First use: {list1}\")\n",
    "print(f\"Second use: {list2}\")\n",
    "\n",
    "# Solution: Use a list if you need to reuse data\n",
    "data = [x * 2 for x in range(5)]  # Can use multiple times\n",
    "print(f\"\\nReusable list: {data}\")\n",
    "print(f\"Can use again: {data[:3]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "335d9c48",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. Mutable Default Arguments\n",
    "print(\"=== Mutable Default Arguments Demo ===\")\n",
    "\n",
    "\n",
    "# Problem: Default list gets modified\n",
    "def add_item_bad(item, my_list=[]):  # DON'T DO THIS\n",
    "    my_list.append(item)\n",
    "    return my_list\n",
    "\n",
    "\n",
    "list1 = add_item_bad(\"apple\")  # [\"apple\"]\n",
    "list2 = add_item_bad(\"banana\")  # [\"apple\", \"banana\"] - Oops!\n",
    "\n",
    "print(f\"First call: {list1}\")\n",
    "print(f\"Second call: {list2}\")  # Both reference the same list!\n",
    "\n",
    "\n",
    "# Solution: Use None as default\n",
    "def add_item_good(item, my_list=None):\n",
    "    if my_list is None:\n",
    "        my_list = []\n",
    "    my_list.append(item)\n",
    "    return my_list\n",
    "\n",
    "\n",
    "list3 = add_item_good(\"apple\")\n",
    "list4 = add_item_good(\"banana\")\n",
    "print(f\"\\nCorrect - First call: {list3}\")\n",
    "print(f\"Correct - Second call: {list4}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b9fb72e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. Overly Complex Comprehensions\n",
    "print(\"=== Complex Comprehensions Demo ===\")\n",
    "# Example data for demonstration\n",
    "data = [[\"apple\", \"banana\", \"cherry\"], [\"#skip\", \"hello\", \"world\"]]\n",
    "\n",
    "# Too complex - hard to read\n",
    "result_complex = [\n",
    "    x.strip().upper()\n",
    "    for sublist in data\n",
    "    for x in sublist\n",
    "    if x and len(x) > 3\n",
    "    if not x.startswith(\"#\")\n",
    "]\n",
    "\n",
    "print(f\"Complex comprehension result: {result_complex}\")\n",
    "\n",
    "# Better - use regular loops for complex logic\n",
    "result_clear = []\n",
    "for sublist in data:\n",
    "    for x in sublist:\n",
    "        if x and len(x) > 3 and not x.startswith(\"#\"):\n",
    "            result_clear.append(x.strip().upper())\n",
    "\n",
    "print(f\"Clear loop result: {result_clear}\")\n",
    "print(f\"Results are equal: {result_complex == result_clear}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7fca8cd",
   "metadata": {},
   "source": [
    "## Best Practices\n",
    "\n",
    "1. **Start Simple:** Use basic comprehensions before trying advanced features\n",
    "2. **Readability First:** If a one-liner is hard to understand, use multiple lines\n",
    "3. **Memory Awareness:** Use generators for large datasets\n",
    "4. **F-strings Everywhere:** Replace old `.format()` and `%` formatting\n",
    "5. **Context Managers:** Always use `with` for files and resources\n",
    "6. **Meaningful Names:** Even in comprehensions, use clear variable names\n",
    "\n",
    "## Quick Reference by Use Case\n",
    "\n",
    "| I Want To...                | Use This Pattern           | Example                             |\n",
    "| --------------------------- | -------------------------- | ----------------------------------- |\n",
    "| Transform a list            | List comprehension         | `[x*2 for x in numbers]`            |\n",
    "| Filter a list               | List comprehension with if | `[x for x in numbers if x > 0]`     |\n",
    "| Build a dictionary          | Dict comprehension         | `{k: v*2 for k, v in data.items()}` |\n",
    "| Format strings              | F-strings                  | `f\"Hello {name}\"`                   |\n",
    "| Process pairs               | zip()                      | `for a, b in zip(list1, list2):`    |\n",
    "| Get index + value           | enumerate()                | `for i, val in enumerate(items):`   |\n",
    "| Handle large data           | Generator expression       | `(x*2 for x in huge_list)`          |\n",
    "| Open files safely           | with statement             | `with open(file) as f:`             |\n",
    "| Avoid repeated calculations | Walrus operator            | `if (n := len(data)) > 10:`         |\n",
    "\n",
    "---\n",
    "\n",
    "_Remember: The best code is readable code. Use these patterns to make your code clearer, not more complex!_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ac3f63b",
   "metadata": {},
   "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.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
