Lists, Tuples & Dictionaries
Lists, Tuples & Dictionaries
1. Lists
Key Features:
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
Key Features:
Extended Unpacking:
values = (1, 2, 3, 4, 5)
a, *b, c = values # a=1, b=[2,3,4], c=5
Common Mistakes:
3. Dictionaries
Key Features:
Mutable: Add, update, or delete key-value pairs.
Keys: Must be unique and immutable (e.g., strings, numbers,
tuples).
Methods:
Example:
Common Mistakes:
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!
7. Real-World Applications
1. Lists:
8. Key Takeaways