Lists, Tuples & Dictionaries
Goal: Master Python’s core data structures—lists (mutable), tuples
(immutable), and dictionaries (key-value pairs).
1. Lists
Definition: Ordered, mutable collections of items.
Syntax: Enclosed in [].
fruits = ["apple", "banana", "cherry"]
mixed_list = [10, "hello", 3.14, True]
Key Features:
Mutable: Modify, add, or remove items.
Indexable: Access items via indices (e.g., fruits[0] → "apple").
Methods:
o .append(item): Add to the end.
o .insert(index, item): Insert at a specific position.
o .remove(item): Delete the first occurrence.
o .pop(index): Remove and return an item.
Example:
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.insert(1, 99) # [1, 99, 2, 3, 4]
numbers.pop(2) # Removes 2 → [1, 99, 3, 4]
Common Mistakes:
Indexing beyond the list length (e.g., accessing list[14] for a 14-
element list → raises IndexError).
Confusing .append() with .extend():
nums = [1, 2]
nums.append([3, 4]) # [1, 2, [3, 4]]
nums.extend([3, 4]) # [1, 2, 3, 4]
2. Tuples
Definition: Ordered, immutable collections.
Syntax: Enclosed in ().
coordinates = (4, 5)
rgb = ("red", "green", "blue")
Key Features:
Immutable: Cannot modify after creation.
Use Cases: Fixed data (e.g., days of the week, database records).
Packing/Unpacking:
point = (3, 7)
x, y = point # x=3, y=7
Extended Unpacking:
values = (1, 2, 3, 4, 5)
a, *b, c = values # a=1, b=[2,3,4], c=5
Common Mistakes:
Trying to modify a tuple:
rgb[0] = "pink" # TypeError: Tuples are immutable!
3. Dictionaries
Definition: Unordered collections of key-value pairs.
Syntax: Enclosed in {}, with key: value pairs.
user = {"name": "Alice", "age": 30, "is_student": False}
Key Features:
Mutable: Add, update, or delete key-value pairs.
Keys: Must be unique and immutable (e.g., strings, numbers,
tuples).
Methods:
o .get(key, default): Returns value or default if key is missing.
o .update(other_dict): Merge dictionaries.
o .keys(): Returns all keys.
o .values(): Returns all values.
Example:
grades = {"math": 90, "science": 85}
grades["history"] = 88 # Add new key
print(grades.get("art", 0)) # Output: 0 (key not found)
grades.update({"math": 95}) # Update existing key
Common Mistakes:
Using mutable keys (e.g., lists):
invalid_dict = {[1, 2]: "data"} # TypeError: Unhashable type.
Case sensitivity: grades.get("Math") ≠ grades["math"].
4. Comparing Data Structures
Feature List Tuple Dictionary
Mutable? Yes No Yes (keys)
Ordered
Yes Yes No (Python 3.7+ preserves insertion order)
?
Fixed
Use Case Dynamic data Key-value mappings
data
5. Iterating Through Data Structures
1. Lists/Tuples:
for item in fruits:
print(item)
2. Dictionaries:
for key, value in user.items():
print(f"{key}: {value}")
Example:
python
Copy
Download
sentence = "the quick brown fox"
word_counts = {}
for word in sentence.split():
word_counts[word] = len(word)
# Output: {"the": 3, "quick": 5, "brown": 5, "fox": 3}
6. Common Pitfalls
1. Accidental Aliasing:
list1 = [1, 2, 3]
list2 = list1 # Both point to the same object!
list2.append(4) # Modifies list1 too!
Fix: Use list2 = list1.copy().
2. Overwriting Keys:
data = {"a": 1, "a": 2} # Last key wins → {"a": 2}.
3. Assuming Order in Dictionaries:
o Pre-Python 3.7, dictionaries don’t preserve order.
7. Real-World Applications
1. Lists:
o Storing user inputs.
o Managing dynamic datasets (e.g., sensor readings).
2. Tuples:
o Representing fixed configurations (e.g., RGB values).
o Returning multiple values from functions.
3. Dictionaries:
o JSON data handling.
o Counting occurrences (e.g., word frequency).
8. Key Takeaways
1. Lists for flexible, ordered collections.
2. Tuples for immutable data.
3. Dictionaries for efficient key-value lookups.
4. Avoid indexing errors and unintended mutations.