Ch2. Python — Data Structures: Lists, Dicts, Tuples & Sets
Python’s Four Core Data Structures
| Structure | Ordered | Mutable | Duplicates | Example |
|---|---|---|---|---|
| list | Yes | Yes | Yes | [1, 2, 3] |
| tuple | Yes | No | Yes | (1, 2, 3) |
| dict | Yes (3.7+) | Yes | Keys: No | {"a": 1} |
| set | No | Yes | No | {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}
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}")
# Alice: 89.0
# Charlie: 91.3
# Bob: 78.3
Chapter 3 Preview
Next: Functions & Object-Oriented Programming — writing reusable functions, classes, inheritance, and encapsulation.
O
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.