Day 13: Tuples and Sets

Students, Day 13: Other collections! Tuples are like lists but immutable (unchangeable): colors = ("red", "green", "blue")—parentheses. Print it; access like lists (colors[0]), but can't modify (uncomment line to see error). Good for fixed data.

Sets: numbers = {1, 2, 3, 2}—curly braces, auto-removes duplicates (becomes {1,2,3}). Unordered, no indexes. numbers.add(4) adds if not present; numbers.remove(2) deletes (errors if missing—use .discard() to avoid). Print shows changes.

Run: Tuple stays fixed, set changes. In 10-15 min, try set operations like union (). Tuples for constants, sets for unique items. Expands lists!

colors = ("red", "green", "blue")  # Tuple
print("Tuple:", colors)
# colors[0] = "yellow"  # This would error!

numbers = {1, 2, 3, 2}  # Set (duplicates auto-removed)
print("Set:", numbers)
numbers.add(4)
numbers.remove(2)
print("Modified Set:", numbers)

Key Concepts:

  • Tuple: An ordered, immutable collection using parentheses (). Can't change after creation.
  • Set: An unordered, mutable collection of unique items using curly braces {}. No duplicates allowed.
  • Immutability: Property where data can't be modified after creation (e.g., tuples).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top