Skip to main content
Albero Academy

Tuples & Sets

Understand immutable tuples and unique-element sets — creation, operations, methods, use cases, and when to use which.

Chapter 6Python16 min readBeginner friendly
  • #Python
  • #Tuples
  • #Sets

Tuples and sets round out the four built-in collection types (list, tuple, set, dict). Tuples are immutable sequences — like read-only lists. Sets are unordered collections of unique elements.

Creating tuples

Python
# Parentheses — most common
point = (10, 20)
rgb = (255, 100, 50)
# Parens are optional but recommended
point2 = 10, 20
# Single-element tuple — comma is REQUIRED
single = (42,) # tuple
not_a_tuple = (42) # just an int in parens
# Empty tuple
empty = ()
# From an iterable
chars = tuple("hello") # ('h', 'e', 'l', 'l', 'o')

When to use a tuple instead of a list

  • The collection should not change — coordinates, RGB triples, database rows.
  • You need it to be hashable — tuples can be dictionary keys; lists cannot.
  • You're returning multiple values from a function — Python returns a tuple by default.
  • You want a small performance edge — tuples are slightly faster to create and iterate.
Python
def location():
return 28.6139, 77.2090 # returns a tuple
lat, lon = location()
print(lat, lon)
# Tuple as dict key — common for caching grids
distances = {}
distances[(0, 0)] = 0
distances[(1, 0)] = 1.0

Tuple unpacking

Python
# Basic unpack
x, y = (10, 20)
print(x, y) # 10 20
# Swap variables — no temp var needed
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# Star unpacking — collect "the rest"
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# In iteration with enumerate
for i, fruit in enumerate(["apple", "mango", "kiwi"]):
print(f"{i}: {fruit}")

Creating sets

Sets store unique elements with no defined order. Membership tests are O(1).

Python
# Curly braces — most common
fruits = {"apple", "mango", "banana"}
# From an iterable — duplicates are removed
unique = set([1, 2, 2, 3, 3, 3, 4])
# {1, 2, 3, 4}
# ⚠️ Empty set — must use set(), NOT {}
empty = set() # {} would create an empty DICT
# Adding & removing
fruits.add("kiwi")
fruits.discard("apple") # no error if missing
fruits.remove("mango") # KeyError if missing
# Membership — fast even for huge sets
print("apple" in fruits)

Set operations

OperationOperatorMethod
Union (a ∪ b)a | ba.union(b)
Intersection (a ∩ b)a & ba.intersection(b)
Difference (a - b)a - ba.difference(b)
Symmetric diffa ^ ba.symmetric_difference(b)
Subseta <= ba.issubset(b)
Superseta >= ba.issuperset(b)
Python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1, 2, 3, 4, 5, 6} union
print(a & b) # {3, 4} intersection
print(a - b) # {1, 2} in a but not b
print(a ^ b) # {1, 2, 5, 6} xor / symmetric diff
# Practical: find users active on both platforms
ios_users = {"u1", "u2", "u3", "u4"}
web_users = {"u3", "u4", "u5"}
both = ios_users & web_users # {'u3', 'u4'}
mobile_only = ios_users - web_users # {'u1', 'u2'}

frozenset

Python
tags = frozenset(["python", "ml", "interview"])
# tags.add("data") # AttributeError — immutable
# Can be a dict key
groups = {
frozenset(["python", "ml"]): "Data Science cohort",
frozenset(["sql", "powerbi"]): "Analytics cohort"
}

Key takeaways

  1. 01Tuples are immutable lists — use them for fixed-shape data, dict keys, and multi-value returns.
  2. 02A single-element tuple needs a trailing comma: (42,).
  3. 03Tuple unpacking (incl. star *) makes Python idiomatic — swap, destructure, iterate.
  4. 04Sets are unordered, unique, with O(1) membership — perfect for dedupe and overlap checks.
  5. 05Use set() for an empty set; {} is an empty dict.
  6. 06Reach for set operators (|, &, -, ^) for clean overlap/diff logic.
  7. 07frozenset is the immutable, hashable cousin — use as dict keys or set-of-sets.