Tuples and Sets
# Tuples and Sets
Welcome to Chapter 11! After mastering lists, let's explore two more essential data structures: tuples (immutable sequences) and sets (unique, unordered collections).
---
1. Learning Objectives
- Create and use tuples and their methods.
- Understand immutability and when to use tuples vs lists.
- Create sets and perform set operations.
- Use frozensets for immutable sets.
---
2. Tuples
Creating Tuples
```python id="py11ex1" # Creating tuples colors = ("red", "green", "blue") single = (42,) # Single element tuple needs comma! noparens = 1, 2, 3 # Parentheses are optional empty = () from_list = tuple([1, 2, 3])
print(colors) # ('red', 'green', 'blue') print(type(colors)) # <class 'tuple'>
python id="py11_ex2" coords = (10, 20, 30, 40, 50)
# Indexing and slicing (same as lists) print(coords[0]) # 10 print(coords[-1]) # 50 print(coords[1:3]) # (20, 30)
# Methods (only 2!) print(coords.count(20)) # 1 print(coords.index(30)) # 2
# Length, min, max, sum print(len(coords)) # 5 print(sum(coords)) # 150
# Tuple unpacking x, y, z = (1, 2, 3) print(f"x={x}, y={y}, z={z}")
# Extended unpacking first, *rest = (1, 2, 3, 4, 5) print(first) # 1 print(rest) # [2, 3, 4, 5]
# Tuples are IMMUTABLE # coords[0] = 99 # ❌ TypeError!
python id="py11ex3" # 1. As dictionary keys (lists can't be keys) locations = {(40.7, -74.0): "New York", (51.5, -0.1): "London"}
# 2. Function return values def getuser(): return "Alice", 25, "alice@email.com"
name, age, email = get_user() print(f"{name}, {age}, {email}")
# 3. Data integrity — prevent accidental modification DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
python id="py11ex4" # Creating sets — unordered, unique elements fruits = {"apple", "banana", "cherry"} numbers = {1, 2, 3, 2, 1} # Duplicates removed! print(numbers) # {1, 2, 3}
# From list (removes duplicates) names = ["Alice", "Bob", "Alice", "Charlie", "Bob"] uniquenames = set(names) print(uniquenames) # {'Alice', 'Bob', 'Charlie'}
# Empty set (NOT {}, that's a dict!) emptyset = set()
python id="py11_ex5" colors = {"red", "green", "blue"}
# Adding colors.add("yellow") colors.update(["purple", "orange"]) print(colors)
# Removing colors.remove("red") # Raises KeyError if not found colors.discard("pink") # No error if not found popped = colors.pop() # Remove random element
# Membership (very fast — O(1)) print("blue" in colors) # True
python id="py11_ex6" a = {1, 2, 3, 4, 5} b = {4, 5, 6, 7, 8}
# Union (all elements) print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8} print(a.union(b))
# Intersection (common elements) print(a & b) # {4, 5} print(a.intersection(b))
# Difference (in a but not b) print(a - b) # {1, 2, 3} print(a.difference(b))
# Symmetric difference (in a or b but not both) print(a ^ b) # {1, 2, 3, 6, 7, 8}
# Subset and superset print({1, 2}.issubset(a)) # True print(a.issuperset({1, 2})) # True
Set Operations Visualization: A = {1,2,3,4,5} B = {4,5,6,7,8}
Union (A | B): {1,2,3,4,5,6,7,8} Intersection (A & B): {4,5} Difference (A - B): {1,2,3} Sym. Diff (A ^ B): {1,2,3,6,7,8}
python id="py11_ex7" squares = {x**2 for x in range(10)} print(squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
python id="py11ex8" fs = frozenset([1, 2, 3]) # fs.add(4) # ❌ AttributeError!
# Can be used as dictionary key or set element setsof_sets = {frozenset([1, 2]), frozenset([3, 4])}
python id="py11_ex9" items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] unique = list(dict.fromkeys(items)) print(unique) # [3, 1, 4, 5, 9, 2, 6]
python id="py11_ex10"
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = list(set(list1) & set(list2))
print(f"Common: {common}") # [4, 5]
``
---
7. MCQs with Answers
Q1: Tuples are: A) Mutable B) Immutable C) Unordered D) Unique-only Answer: B
Q2: Empty set is created by:
A) {} B) set() C) () D) []
Answer: B — {} creates an empty dict.
Q3: {1,2,3} & {2,3,4} returns:
A) {1,2,3,4} B) {2,3} C) {1,4} D) Error
Answer: B — Intersection.
Q4: Can sets contain lists? A) Yes B) No Answer: B — Sets require hashable (immutable) elements.
Q5: (42,) is a:
A) Integer B) Tuple C) List D) Set
Answer: B — The comma makes it a tuple.
Q6: Single-element tuple without comma:
A) (42) is a tuple B) (42) is an integer C) Error D) None
Answer: B
Q7: Set membership check time complexity: A) O(n) B) O(log n) C) O(1) D) O(n²) Answer: C — Hash table lookup.
Q8: frozenset is:
A) Mutable set B) Immutable set C) Frozen list D) Constant
Answer: B
Q9: Tuples can be dict keys: A) Yes B) No Answer: A — Because they're immutable/hashable.
Q10: set([1,1,2,2,3]) returns:
A) [1,2,3] B) {1,2,3} C) (1,2,3) D) Error
Answer: B
---
8. Interview Questions
- 1. When to use tuple vs list? Tuples for fixed, immutable data (coordinates, RGB). Lists for dynamic collections.
- 2. Why are tuples faster than lists? Less memory overhead; Python optimizes immutable objects.
-
3.
How to remove duplicates from a list? list(set(data))
orlist(dict.fromkeys(data))for order.
-
4.
Can you have a set of sets? Not directly. Use frozenset
elements.
-
5.
What is tuple packing and unpacking? Packing: t = 1, 2, 3
. Unpacking:a, b, c = t.
---
9. Summary
- Tuples are immutable, ordered sequences — use for fixed data, dict keys, function returns.
- Sets are mutable, unordered, unique-element collections — use for deduplication and set math.
- Frozensets are immutable sets.
-
Set operations: union (|
), intersection (&), difference (-), symmetric difference (^`).
---
10. Next Chapter Recommendation
In Chapter 12: Dictionaries in Python, you'll master key-value pairs, the most powerful data structure for real-world programming! 🚀