INFS1201 Computer Programming

Lesson 9: Tuples and Sets • Mohammed Shifan

Lesson 9: Tuples and Sets

Data that cannot change (tuples) and data with no duplicates (sets) • Appendix G (Tuples & Sets)

1. Tuples: Ordered & Immutable Sequences

A tuple is an ordered sequence of values, exactly like a list, except that it can never be modified once created.

color = (255, 180, 30)
print(color[0])  # 255 (indexing works!)

# ❌ The write is refused:
color[0] = 200
# TypeError: 'tuple' object does not support item assignment
⚠️ The Comma Trap: It is the comma that creates a tuple, not the brackets!
a = (42) → integer 42 in parentheses (type: int).
b = (42,) → a 1-tuple (type: tuple).
len((42)) raises TypeError: object of type 'int' has no len(). The only exception without a comma is the empty tuple ().

2. Tuple Unpacking & Why Use Tuples

Tuple Unpacking

Assigns each element of a tuple to a distinct variable name in one clean line.

student = ("Ahmed", 60012345, 3.6)
(name, sid, gpa) = student
print(name)  # "Ahmed"
print(sid)   # 60012345

# The Python Swap Trick:
a, b = 10, 20
a, b = b, a  # Packs right side into tuple, unpacks into left!
⚠️ Count Must Match: The number of variable names on the left must exactly equal the number of items in the tuple, otherwise Python raises ValueError: too many values to unpack.

Why Use Tuples?

  • Protect your data: Functions cannot modify what they cannot write to. Pass a tuple, and your data is guaranteed untouched.
  • Return multiple values: Functions can easily hand back 2 or 3 values together:
    def largest_value(data):
        largest = max(data)
        location = data.index(largest)
        return largest, location  # returns tuple!
    
    val, idx = largest_value([40, 56, 20])
  • Standard library returns: os.path.splitext(), divmod(), and enumerate() all hand back tuples.

3. Sets: Unique, Unordered Collections

A set is an unordered collection of unique values. Adding a duplicate value changes nothing, and elements do not have indexed positions.

grades = [88, 92, 88, 75, 92, 88]
unique = set(grades)
print(unique)          # e.g. {92, 75, 88} (duplicates eliminated!)
print(sorted(unique))  # [75, 88, 92] (predictable list order)
⚠️ Crucial Rules for Sets:
  • No duplicates: Automatically dropped.
  • No indexing: unique[0] raises TypeError: 'set' object is not subscriptable.
  • Empty set syntax: {} creates an empty dictionary! The only way to create an empty set is set().
⚡ Why Sets Are Fast (Hashing):
A list scans every item one by one ($O(N)$). A set calculates a hash number that points directly to the exact slot ($O(1)$). In a test of 100,000 searches, set lookups were over 200 times faster than list lookups!

4. Set Methods & The Four Set Operations

Set Modification Methods

Method What It Does
s.add(x) Adds x. If already present, does nothing.
s.remove(x) Removes x. Raises KeyError if missing!
s.discard(x) Removes x if present; stays silent if not.
s.clear() Empties the set completely.
x in s Fast membership test (returns True / False).

The Four Set Operations (Venn Diagram)

Operator Method Meaning
a | b a.union(b) All values in either set (no duplicates).
a & b a.intersection(b) Only values present in both sets.
a - b a.difference(b) Values in a that are not in b.
a ^ b a.symmetric_difference(b) Values in exactly one set, but not both.
Operator vs Method: The named method accepts lists (e.g. a.union([3, 4])), while the operator | requires both sides to be sets.

5. Summary Comparison: Lists vs Tuples vs Sets

Feature List ([]) Tuple (()) Set ({} / set())
Preserves insertion order ✓ Yes ✓ Yes ✕ No
Can be modified (mutable) ✓ Yes ✕ No (Locked) ✓ Yes (add/remove)
Duplicates permitted ✓ Yes ✓ Yes ✕ No (Unique only)
Indexing & Slicing with [] ✓ Yes ✓ Yes ✕ No
Fast membership search (in) ✕ Slow ($O(N)$) ✕ Slow ($O(N)$) ✓ Super fast ($O(1)$)
Score: 0 / 8

Practice Challenges & Solutions

← Previous: Lesson 8 (Nested Lists & 2D Data) Return to Portal Home 🎓
🎓

Enter Student Name

Please enter your full name as you would like it to appear on your Certificate.

INFS1201 Computer Programming • Lesson 9 Assessment

Certificate of Completion

presented to

Student Name

for successfully mastering Lesson 9 with a score of

0 / 8

Date
Mohammed Shifan
Awarded by