{ "cells": [ { "cell_type": "markdown", "id": "f516f36b", "metadata": {}, "source": [ "# Python Basics - 03. Data Structures\n", "\n", "To write efficient programs, you need ways to organize and store data. Python provides four fundamental built-in data structures: Lists, Tuples, Dictionaries, and Sets." ] }, { "cell_type": "markdown", "metadata": { "language": "markdown" }, "source": [ "## Download Notebook\n", "\n", "{download}`Download this notebook <03_data_structures.ipynb>`\n" ] }, { "cell_type": "markdown", "id": "a269829c", "metadata": {}, "source": [ "## 1. Lists (Ordered, Mutable array)\n", "\n", "A `list` is a collection of ordered, mutable (changeable) elements. They are defined using square brackets `[]`." ] }, { "cell_type": "code", "execution_count": null, "id": "08b3a007", "metadata": {}, "outputs": [], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "print(f\"Initial list: {fruits}\")\n", "\n", "# Accessing elements (0-indexed)\n", "print(f\"Element at index 1: {fruits[1]}\")\n", "\n", "# Modifying an element (Mutable)\n", "fruits[0] = \"apricot\"\n", "print(f\"After modification: {fruits}\")\n", "\n", "# Adding elements\n", "fruits.append(\"orange\") # Adds to the end\n", "print(f\"After append: {fruits}\")\n", "\n", "# Removing an element by value\n", "fruits.remove(\"banana\")\n", "print(f\"After remove: {fruits}\")" ] }, { "cell_type": "markdown", "id": "1bdd4978", "metadata": {}, "source": [ "## 2. Tuples (Ordered, Immutable array)\n", "\n", "A `tuple` works just like a list, but it is **immutable** (you cannot change its contents after creation). They are defined using parentheses `()`." ] }, { "cell_type": "code", "execution_count": null, "id": "61a0f71f", "metadata": {}, "outputs": [], "source": [ "coords = (10, 20.5, 30.1)\n", "print(f\"Coordinates tuple: {coords}\")\n", "print(f\"X Coordinate: {coords[0]}\")\n", "\n", "# Uncommenting the line below will result in an error!\n", "# coords[0] = 15 # TypeError: 'tuple' object does not support item assignment" ] }, { "cell_type": "markdown", "id": "e44ca4a9", "metadata": {}, "source": [ "## 3. Dictionaries (Key-Value mappings)\n", "\n", "A `dictionary` is an unordered collection of data stored as key-value pairs. They allow fast lookups based on keys, and are defined using curly braces `{}`." ] }, { "cell_type": "code", "execution_count": null, "id": "fa1ab801", "metadata": {}, "outputs": [], "source": [ "person = {\n", " \"name\": \"Alice\", \n", " \"age\": 25, \n", " \"city\": \"New York\"\n", "}\n", "print(f\"Dictionary: {person}\")\n", "\n", "# Accessing a value by its key\n", "print(f\"Person's name: {person['name']}\")\n", "\n", "# Adding or updating a key-value pair\n", "person[\"email\"] = \"alice@example.com\" # Adding a new key\n", "person[\"age\"] = 26 # Updating an existing key\n", "print(f\"Updated dictionary: {person}\")\n", "\n", "# Removing a key-value pair\n", "del person[\"city\"]\n", "print(f\"After deleting 'city': {person}\")" ] }, { "cell_type": "markdown", "id": "0360d8f3", "metadata": {}, "source": [ "## 4. Sets (Unordered, Unique elements)\n", "\n", "A `set` is a collection of unordered elements where every item must be **unique**. They are very useful for mathematical set operations or deduplicating lists." ] }, { "cell_type": "code", "execution_count": null, "id": "df868152", "metadata": {}, "outputs": [], "source": [ "# Notice duplicate '3' and '4' are defined\n", "numbers = {1, 2, 3, 3, 4, 4, 5}\n", "print(f\"Set (duplicates automatically removed): {numbers}\")\n", "\n", "numbers.add(6)\n", "print(f\"Added 6: {numbers}\")\n", "\n", "# Checking membership is very fast in a set\n", "print(f\"Is the number 3 inside the set? {3 in numbers}\")" ] }, { "cell_type": "markdown", "id": "8bce2deb", "metadata": {}, "source": [ "## 5. Copying, Nested Structures, and Common Pitfalls\n", "\n", "When data structures become nested, shallow vs deep copy matters:\n", "- `copy()` creates a shallow copy (outer container copied, inner objects shared).\n", "- `deepcopy()` recursively copies nested objects.\n", "\n", "You should also know safe dictionary access with `get()` to avoid `KeyError`." ] }, { "cell_type": "code", "execution_count": null, "id": "521f645b", "metadata": {}, "outputs": [], "source": [ "from copy import deepcopy\n", "\n", "# Nested mutable data structure\n", "original = {\n", " \"user\": \"Alice\",\n", " \"skills\": [\"python\", \"sql\"]\n", "}\n", "\n", "# Shallow copy: top-level dict is copied, but nested list is shared.\n", "shallow = original.copy()\n", "\n", "# Deep copy: full recursive copy, nested list is independent.\n", "deep = deepcopy(original)\n", "\n", "# Modifying nested list in shallow copy also affects original.\n", "shallow[\"skills\"].append(\"linux\")\n", "print(\"Original after shallow change:\", original)\n", "print(\"Shallow:\", shallow)\n", "print(\"Deep:\", deep)\n", "\n", "# Safe dictionary access with get()\n", "# get(\"missing\") returns None instead of raising KeyError.\n", "data = {\"name\": \"Bob\"}\n", "print(data.get(\"age\")) # None\n", "print(data.get(\"age\", \"N/A\")) # Default fallback value" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }