
Python — Data Structures & Selection Criteria
Python’s Four Core Data Structures
| Structure | Properties and example |
|---|---|
| list | Ordered, mutable, duplicates allowed. Example: [1, 2, 3]. |
| tuple | Ordered, fixed item references, duplicates allowed. Example: (1, 2, 3). Referenced mutable objects can still change. |
| dict | Insertion order guaranteed since Python 3.7; mutable; keys are unique and must be hashable. Example: {"a": 1}. |
| set | No positional order guarantee; mutable; unique hashable elements. Example: {1, 2, 3}. |
Lists
fruits = ["apple", "banana", "cherry", "apple"]
# Indexing (0-based)
print(fruits[0]) # apple
print(fruits[-1]) # apple (last item)
# Slicing
print(fruits[1:3]) # ['banana', 'cherry']
# Key methods
fruits.append("mango") # Add to end
fruits.insert(1, "grape") # Insert at index 1
fruits.remove("banana") # Remove by value
fruits.pop() # Remove last item
fruits.sort() # Sort in place
print(len(fruits)) # Length
# List comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Conditional comprehension
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Dictionaries
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Access
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("job", "Unknown")) # Unknown (default if missing)
# Add / modify
person["email"] = "alice@example.com"
person["age"] = 31
# Delete
del person["city"]
# Iterate
for key, value in person.items():
print(f"{key}: {value}")
# Dictionary comprehension
word_lengths = {word: len(word) for word in ["python", "java", "javascript"]}
# {'python': 6, 'java': 4, 'javascript': 10}
Tuples and Sets
# Tuples: immutable sequences (good for coordinates, RGB values)
coordinates = (40.7128, -74.0060) # NYC coordinates
lat, lon = coordinates # Unpacking
# Sets: unordered, no duplicates
numbers = {1, 2, 3, 3, 4, 4, 5}
print(numbers) # {1, 2, 3, 4, 5}
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
Nested mutation and shallow copies
A tuple fixes its element references, not the objects they point to. Hashability is a separate requirement: a tuple containing a list is unhashable. Mutable user-defined instances can still be hashable by identity; do not infer hashability from mutability alone.
bundle = (["draft"],)
bundle[0].append("reviewed")
assert bundle == (["draft", "reviewed"],)
try:
hash(bundle)
except TypeError:
print("The nested list makes this tuple unhashable.")
A shallow copy creates an outer container but shares its nested objects. With the built-in objects below, a deep copy instead creates an independent nested list. Deep copying is not a universal way to duplicate resources such as files or network connections.
from copy import deepcopy
original = {"tags": ["draft"]}
shallow = dict(original)
independent = deepcopy(original)
shallow["tags"].append("reviewed")
assert shallow is not original
assert original["tags"] == ["draft", "reviewed"]
assert independent["tags"] == ["draft"]
Chapter 8’s wordbook can use a shallow candidate copy because its validated keys and values are strings. Introducing nested mutable values would require revisiting that assumption. Dictionary keys also use equality: True, 1, and 1.0 compare equal and address the same entry. Validate identifiers if booleans and integers must be distinct in your application.
See the hashable definition and copy semantics.
Practical Example: Grade Manager
students = {
"Alice": [90, 85, 92],
"Bob": [78, 82, 75],
"Charlie": [95, 88, 91]
}
# Calculate averages with dict comprehension
averages = {
name: sum(scores) / len(scores)
for name, scores in students.items()
}
# Sort and display
for name, avg in sorted(averages.items(), key=lambda x: x[1], reverse=True):
print(f"{name}: {avg:.1f}")
# Charlie: 91.3
# Alice: 89.0
# Bob: 78.3
collections: Advanced Data Structures
from collections import Counter, defaultdict, deque
# Counter: count element frequencies
text = "hello world python programming"
word_count = Counter(text.split())
print(word_count.most_common(3))
# defaultdict: auto-create missing keys
grades = defaultdict(list)
grades["Alice"].append(90)
grades["Alice"].append(85)
# deque: double-ended queue
queue = deque([1, 2, 3])
queue.appendleft(0) # Add to left
queue.append(4) # Add to right
queue.popleft() # Remove from left
Chapter 6 Preview
Next: Files, Serialization & Exceptions.
OIYO Editorial
Editorial DeskThe OIYO editorial desk researches money, law, lifestyle, and self-understanding topics against primary sources and public statistics. Every piece carries source notes and is reviewed on a regular cycle for accuracy and usefulness.