From 54338a8d6c6144b4a112e9d9cf9aca7634b877a3 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:18:49 +0000 Subject: [PATCH] Add python-data-structures materials folder Sample code for the Common Python Data Structures (Guide) tutorial, one script per section, mirroring the code in the update draft. --- python-data-structures/README.md | 25 +++++ python-data-structures/arrays.py | 91 +++++++++++++++++ python-data-structures/dictionaries.py | 55 ++++++++++ python-data-structures/priority_queues.py | 32 ++++++ python-data-structures/queues.py | 53 ++++++++++ python-data-structures/records.py | 117 ++++++++++++++++++++++ python-data-structures/sets.py | 32 ++++++ python-data-structures/stacks.py | 45 +++++++++ 8 files changed, 450 insertions(+) create mode 100644 python-data-structures/README.md create mode 100644 python-data-structures/arrays.py create mode 100644 python-data-structures/dictionaries.py create mode 100644 python-data-structures/priority_queues.py create mode 100644 python-data-structures/queues.py create mode 100644 python-data-structures/records.py create mode 100644 python-data-structures/sets.py create mode 100644 python-data-structures/stacks.py diff --git a/python-data-structures/README.md b/python-data-structures/README.md new file mode 100644 index 0000000000..e8d51ac92f --- /dev/null +++ b/python-data-structures/README.md @@ -0,0 +1,25 @@ +# Common Python Data Structures (Guide) + +This folder provides the code examples for the Real Python tutorial [Common Python Data Structures (Guide)](https://realpython.com/python-data-structures/). + +## Setup + +The examples use only the Python standard library, so there's nothing to install. You need Python 3.7 or later. + +## Usage + +Each script covers one section of the tutorial: + +- `dictionaries.py`: Dictionaries, maps, and hash tables +- `arrays.py`: Array data structures +- `records.py`: Records, structs, and data transfer objects +- `sets.py`: Sets and multisets +- `stacks.py`: Stacks (LIFOs) +- `queues.py`: Queues (FIFOs) +- `priority_queues.py`: Priority queues + +Run any of them with Python: + +```sh +$ python dictionaries.py +``` diff --git a/python-data-structures/arrays.py b/python-data-structures/arrays.py new file mode 100644 index 0000000000..654605de31 --- /dev/null +++ b/python-data-structures/arrays.py @@ -0,0 +1,91 @@ +import array + +# list: Mutable dynamic arrays +arr = ["one", "two", "three"] +print(arr[0]) +print(arr) +arr[1] = "hello" +print(arr) +del arr[1] +print(arr) +# Lists can hold arbitrary data types: +arr.append(23) +print(arr) + +# tuple: Immutable containers +arr = ("one", "two", "three") +print(arr[0]) +print(arr) +try: + arr[1] = "hello" +except TypeError as error: + print(f"TypeError: {error}") +# Adding elements creates a copy of the tuple: +print(arr + (23,)) + +# array.array: Basic typed arrays +arr = array.array("f", (1.0, 1.5, 2.0, 2.5)) +print(arr[1]) +print(arr) +arr[1] = 23.0 +print(arr) +del arr[1] +print(arr) +arr.append(42.0) +print(arr) +# Arrays are "typed": +try: + arr[1] = "hello" +except TypeError as error: + print(f"TypeError: {error}") + +# str: Immutable arrays of Unicode characters +arr = "abcd" +print(repr(arr[1])) +print(repr(arr)) +try: + arr[1] = "e" +except TypeError as error: + print(f"TypeError: {error}") +# Strings can be unpacked into a list to get a mutable representation: +print(list("abcd")) +print(repr("".join(list("abcd")))) +# Strings are recursive data structures: +print(type("abc")) +print(type("abc"[0])) + +# bytes: Immutable arrays of single bytes +arr = bytes((0, 1, 2, 3)) +print(arr[1]) +# Bytes literals have their own syntax: +print(arr) +arr = b"\x00\x01\x02\x03" +# Only valid bytes are allowed: +try: + bytes((0, 300)) +except ValueError as error: + print(f"ValueError: {error}") +try: + arr[1] = 23 +except TypeError as error: + print(f"TypeError: {error}") + +# bytearray: Mutable arrays of single bytes +arr = bytearray((0, 1, 2, 3)) +print(arr[1]) +print(arr) +arr[1] = 23 +print(arr) +print(arr[1]) +# Bytearrays can grow and shrink in size: +del arr[1] +print(arr) +arr.append(42) +print(arr) +# Bytearrays can only hold bytes (integers in the range 0 <= x <= 255): +try: + arr[1] = 300 +except ValueError as error: + print(f"ValueError: {error}") +# Bytearrays can be converted back into bytes objects (this copies the data): +print(bytes(arr)) diff --git a/python-data-structures/dictionaries.py b/python-data-structures/dictionaries.py new file mode 100644 index 0000000000..9441734894 --- /dev/null +++ b/python-data-structures/dictionaries.py @@ -0,0 +1,55 @@ +from collections import ChainMap, OrderedDict, defaultdict +from types import MappingProxyType + +# dict: Your go-to dictionary +phonebook = { + "bob": 7387, + "alice": 3719, + "jack": 7052, +} +squares = {x: x * x for x in range(6)} +print(phonebook["alice"]) +print(squares) + +# collections.OrderedDict: Remember the insertion order of keys +d = OrderedDict(one=1, two=2, three=3) +print(d) +d["four"] = 4 +print(d) +print(d.keys()) + +# collections.defaultdict: Return default values for missing keys +dd = defaultdict(list) +# Accessing a missing key creates it and initializes it +# using the default factory, list() in this example: +dd["dogs"].append("Rufus") +dd["dogs"].append("Kathrin") +dd["dogs"].append("Mr Sniffles") +print(dd["dogs"]) + +# collections.ChainMap: Search multiple dictionaries as a single mapping +dict1 = {"one": 1, "two": 2} +dict2 = {"three": 3, "four": 4} +chain = ChainMap(dict1, dict2) +print(chain) +# ChainMap searches each collection in the chain +# from left to right until it finds the key (or fails): +print(chain["three"]) +print(chain["one"]) +try: + chain["missing"] +except KeyError as error: + print(f"KeyError: {error}") + +# types.MappingProxyType: A wrapper for making read-only dictionaries +writable = {"one": 1, "two": 2} +read_only = MappingProxyType(writable) +# The proxy is read-only: +print(read_only["one"]) +try: + read_only["one"] = 23 +except TypeError as error: + print(f"TypeError: {error}") +# Updates to the original are reflected in the proxy: +writable["one"] = 42 +print(repr(read_only)) diff --git a/python-data-structures/priority_queues.py b/python-data-structures/priority_queues.py new file mode 100644 index 0000000000..059dc26930 --- /dev/null +++ b/python-data-structures/priority_queues.py @@ -0,0 +1,32 @@ +import heapq +from queue import PriorityQueue + +# list: Manually sorted queues +q = [] +q.append((2, "code")) +q.append((1, "eat")) +q.append((3, "sleep")) +# Remember to re-sort every time a new element is inserted, +# or use bisect.insort() +q.sort(reverse=True) +while q: + next_item = q.pop() + print(next_item) + +# heapq: List-based binary heaps +q = [] +heapq.heappush(q, (2, "code")) +heapq.heappush(q, (1, "eat")) +heapq.heappush(q, (3, "sleep")) +while q: + next_item = heapq.heappop(q) + print(next_item) + +# queue.PriorityQueue: Beautiful priority queues +q = PriorityQueue() +q.put((2, "code")) +q.put((1, "eat")) +q.put((3, "sleep")) +while not q.empty(): + next_item = q.get() + print(next_item) diff --git a/python-data-structures/queues.py b/python-data-structures/queues.py new file mode 100644 index 0000000000..b75eb6d2cb --- /dev/null +++ b/python-data-structures/queues.py @@ -0,0 +1,53 @@ +from collections import deque +import multiprocessing +from queue import Empty, Queue + +# list: Terribly sloooow queues +q = [] +q.append("eat") +q.append("sleep") +q.append("code") +print(q) +# Careful: This is slow! +print(q.pop(0)) + +# collections.deque: Fast and robust queues +q = deque() +q.append("eat") +q.append("sleep") +q.append("code") +print(q) +print(q.popleft()) +print(q.popleft()) +print(q.popleft()) +try: + q.popleft() +except IndexError as error: + print(f"IndexError: {error}") + +# queue.Queue: Locking semantics for parallel computing +q = Queue() +q.put("eat") +q.put("sleep") +q.put("code") +print(q) +print(q.get()) +print(q.get()) +print(q.get()) +try: + q.get_nowait() +except Empty: + print("queue.Empty") +# Calling q.get() now would block and wait forever. + +# multiprocessing.Queue: Shared job queues +if __name__ == "__main__": + q = multiprocessing.Queue() + q.put("eat") + q.put("sleep") + q.put("code") + print(q) + print(q.get()) + print(q.get()) + print(q.get()) + # Calling q.get() now would block and wait forever. diff --git a/python-data-structures/records.py b/python-data-structures/records.py new file mode 100644 index 0000000000..b5063cbd6a --- /dev/null +++ b/python-data-structures/records.py @@ -0,0 +1,117 @@ +from collections import namedtuple +from dataclasses import dataclass +import dis +from struct import Struct +from sys import getsizeof +from types import SimpleNamespace +from typing import NamedTuple + +# dict: Simple data objects +car1 = { + "color": "red", + "mileage": 3812.4, + "automatic": True, +} +car2 = { + "color": "blue", + "mileage": 40231, + "automatic": False, +} +print(car2) +print(car2["mileage"]) +car2["mileage"] = 12 +car2["windshield"] = "broken" +print(car2) + +# tuple: Immutable groups of objects +dis.dis(compile("(23, 'a', 'b', 'c')", "", "eval")) +dis.dis(compile("[23, 'a', 'b', 'c']", "", "eval")) + +# Fields: color, mileage, automatic +car1 = ("red", 3812.4, True) +car2 = ("blue", 40231.0, False) +print(car1) +print(car2) +print(car2[1]) + + +# Write a custom class: More work, more control +class Car: + def __init__(self, color, mileage, automatic): + self.color = color + self.mileage = mileage + self.automatic = automatic + + +car1 = Car("red", 3812.4, True) +car2 = Car("blue", 40231.0, False) +print(car2.mileage) +car2.mileage = 12 +car2.windshield = "broken" +# The string representation isn't very useful: +print(car1) + + +# dataclasses.dataclass: Python 3.7+ data classes +@dataclass +class Car: + color: str + mileage: float + automatic: bool + + +car1 = Car("red", 3812.4, True) +print(car1) +print(car1.mileage) +car1.mileage = 12 +car1.windshield = "broken" +# Type annotations aren't enforced without a type checker like mypy: +print(Car("red", "NOT_A_FLOAT", 99)) + +# collections.namedtuple: Convenient data objects +p1 = namedtuple("Point", "x y z")(1, 2, 3) +p2 = (1, 2, 3) +print(getsizeof(p1)) +print(getsizeof(p2)) + +Car = namedtuple("Car", "color mileage automatic") +car1 = Car("red", 3812.4, True) +print(car1) +print(car1.mileage) +try: + car1.mileage = 12 +except AttributeError as error: + print(f"AttributeError: {error}") + + +# typing.NamedTuple: Improved namedtuples +class Car(NamedTuple): + color: str + mileage: float + automatic: bool + + +car1 = Car("red", 3812.4, True) +print(car1) +print(car1.mileage) +try: + car1.windshield = "broken" +except AttributeError as error: + print(f"AttributeError: {error}") +print(Car("red", "NOT_A_FLOAT", 99)) + +# struct.Struct: Serialized C structs +MyStruct = Struct("i?f") +data = MyStruct.pack(23, False, 42.0) +# All you get is a blob of data: +print(data) +# Data blobs can be unpacked again: +print(MyStruct.unpack(data)) + +# types.SimpleNamespace: Fancy attribute access +car1 = SimpleNamespace(color="red", mileage=3812.4, automatic=True) +print(car1) +car1.mileage = 12 +car1.windshield = "broken" +del car1.automatic +print(car1) diff --git a/python-data-structures/sets.py b/python-data-structures/sets.py new file mode 100644 index 0000000000..3249e7bf58 --- /dev/null +++ b/python-data-structures/sets.py @@ -0,0 +1,32 @@ +from collections import Counter + +# set: Your go-to set +vowels = {"a", "e", "i", "o", "u"} +squares = {x * x for x in range(10)} +print("e" in vowels) +letters = set("alice") +print(letters.intersection(vowels)) +vowels.add("x") +print(vowels) +print(len(vowels)) + +# frozenset: Immutable sets +vowels = frozenset({"a", "e", "i", "o", "u"}) +try: + vowels.add("p") +except AttributeError as error: + print(f"AttributeError: {error}") +# Frozensets are hashable and can be used as dictionary keys: +d = {frozenset({1, 2, 3}): "hello"} +print(d[frozenset({1, 2, 3})]) + +# collections.Counter: Multisets +inventory = Counter() +loot = {"sword": 1, "bread": 3} +inventory.update(loot) +print(inventory) +more_loot = {"sword": 1, "apple": 1} +inventory.update(more_loot) +print(inventory) +print(len(inventory)) # Unique elements +print(sum(inventory.values())) # Total number of elements diff --git a/python-data-structures/stacks.py b/python-data-structures/stacks.py new file mode 100644 index 0000000000..5e2263f870 --- /dev/null +++ b/python-data-structures/stacks.py @@ -0,0 +1,45 @@ +from collections import deque +from queue import Empty, LifoQueue + +# list: Simple, built-in stacks +s = [] +s.append("eat") +s.append("sleep") +s.append("code") +print(s) +print(s.pop()) +print(s.pop()) +print(s.pop()) +try: + s.pop() +except IndexError as error: + print(f"IndexError: {error}") + +# collections.deque: Fast and robust stacks +s = deque() +s.append("eat") +s.append("sleep") +s.append("code") +print(s) +print(s.pop()) +print(s.pop()) +print(s.pop()) +try: + s.pop() +except IndexError as error: + print(f"IndexError: {error}") + +# queue.LifoQueue: Locking semantics for parallel computing +s = LifoQueue() +s.put("eat") +s.put("sleep") +s.put("code") +print(s) +print(s.get()) +print(s.get()) +print(s.get()) +try: + s.get_nowait() +except Empty: + print("queue.Empty") +# Calling s.get() now would block and wait forever.