On this page
  1. Built-in Data Structures
  2. Contents
  3. Overview & Mutability
  4. Lists (list), Indexing & Slicing
  5. Tuples (tuple) & Unpacking
  6. Sets (set & frozenset)
  7. Dictionaries (dict)
  8. Comprehensions

Built-in Data Structures

Prev: Primitive Data Types | Up: Core Fundamentals | Next: Control Flow
Rel: list, tuple, set, dict, collections, copy
Ref: docs.python.org — Data Structures
Tags: #public #python3 #tutorials #fundamentals #data-structures


Contents


Overview & Mutability

Type Ordered Mutable Duplicates Hashable Typical Use
list Yes Yes Yes No Homogeneous dynamic sequences
tuple Yes No Yes If elements are Fixed records, dict keys
set No Yes No No (frozenset is) Membership testing, set algebra
dict Insertion Yes Unique keys No Key-value mappings, lookups

Lists (list), Indexing & Slicing

[[__builtins__/list|list]] supports zero-based indexing, negative indexing from the end, and [start:stop:step] slicing.

nums = [10, 20, 30, 40, 50]
print(nums[0], nums[-1])      # 10 50
print(nums[1:4])              # [20, 30, 40]
print(nums[::-1])             # [50, 40, 30, 20, 10]

nums.append(60)
nums.extend([70, 80])
popped = nums.pop()           # 80

Because lists are mutable, assigning b = a aliases the same object; use a.copy() or [[stdlib_module/copy|copy.deepcopy()]] when isolation is needed.


Tuples (tuple) & Unpacking

[[__builtins__/tuple|tuple]] is an immutable sequence. Single-element tuples require a trailing comma: (42,).

point = (3, 4)
x, y = point

first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)    # 1 [2, 3, 4] 5

Sets (set & frozenset)

[[__builtins__/set|set]] provides $O(1)$ average membership checks and mathematical set operations (|, &, -, ^).

a = {"python", "rust", "go"}
b = {"python", "zig", "c"}

print(a | b)   # Union
print(a & b)   # Intersection: {'python'}
print(a - b)   # Difference: {'rust', 'go'}
print(a ^ b)   # Symmetric difference

Dictionaries (dict)

[[__builtins__/dict|dict]] preserves insertion order (guaranteed since Python 3.7) and supports merge (|) and update (|=) operators.

config = {"host": "localhost", "port": 8080}
overrides = {"port": 9090, "debug": True}

merged = config | overrides
print(merged.get("timeout", 30))   # 30

for key, val in merged.items():
    print(f"{key} = {val}")

Comprehensions

Comprehensions construct lists, sets, and dicts concisely without manual .append() loops.

squares = [n * n for n in range(6) if n % 2 == 0]       # [0, 4, 16]
unique_lens = {len(w) for w in ["hi", "hey", "hello"]}  # {2, 3, 5}
index_map = {ch: i for i, ch in enumerate("abc")}       # {'a': 0, 'b': 1, 'c': 2}

Linked from

Related notes