PY

Python Fundamentals

18 lessons

Progress0%
1. Introduction to Python
1What is Python?2Setting Up Python
2. Variables and Data Types
1Variables in Python2Data Types
3. Control Flow
Conditional StatementsLoops
4. Functions
Function Basics
5. Data Structures
Lists Deep DiveTuples & SetsDictionaries & Comprehensions
6. Advanced Functions
Closures & Higher-Order FunctionsDecorators & Lambda
7. Object-Oriented Python
Classes & InstancesInheritance & Dunder Methods
8. Exception Handling
try / except / finallyCustom Exceptions & Context Managers
9. Modules & File I/O
Modules & PackagesFile I/O & JSON
All Tutorials
PythonData Structures
Lesson 9 of 18 min
Chapter 5 · Lesson 2

Tuples & Sets

Tuples & Sets

Python provides two more important built-in collection types: tuples (ordered, immutable) and sets (unordered, mutable, no duplicates).


Tuples

A tuple is like a list that cannot be changed after creation. Use parentheses (or just commas) to define one:

python
point   = (3, 7)
colors  = ("red", "green", "blue")
single  = (42,)   # trailing comma required for single-element tuple
nothing = ()      # empty tuple

Why use tuples?

  • Hashable (can be dict keys or set members)
  • Slightly faster than lists
  • Signal to readers that the data should not change
  • Used as function return values to group multiple items

Tuple Unpacking

Unpacking assigns each element of a tuple to a variable in one statement:

python
x, y = (10, 20)
first, *rest = (1, 2, 3, 4, 5)   # *rest captures remaining items
a, b, c = "ABC"                   # works on any iterable

Named Tuples

collections.namedtuple adds field names without the overhead of a full class:

python
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 7)
print(p.x, p.y)   # 3 7
print(p[0])        # 3  — still index-accessible

Sets

A set is an unordered collection of unique items. It is ideal for membership tests and eliminating duplicates:

python
s = {1, 2, 3, 3, 2}   # {1, 2, 3}
empty_set = set()      # NOT {} — that creates a dict!

Common Set Methods

Method / OperatorMeaning
s.add(x)Add single element
s.remove(x)Remove x; raises KeyError if absent
s.discard(x)Remove x; no error if absent
s.pop()Remove & return an arbitrary element
`ABorA.union(B)`
A & B or A.intersection(B)Elements in both
A - B or A.difference(B)Elements in A but not B
A ^ B or A.symmetric_difference(B)Elements in A or B but not both
A <= B or A.issubset(B)True if A is a subset of B

Frozenset

A frozenset is an immutable set — it can be used as a dictionary key or placed inside another set:

python
fs = frozenset([1, 2, 3])
d  = {fs: "immutable set as key"}   # valid!

When to Use Each

Use caseBest type
Ordered, changeable sequencelist
Ordered, unchangeable recordtuple
Unique membership / set mathset
Immutable set (dict key)frozenset

Code Examples

Tuple Basics & Unpackingpython
# Basic tuple
coordinates = (10.5, 20.3, 5.0)
print("Coordinates:", coordinates)
print("X:", coordinates[0])

# Tuple unpacking
x, y, z = coordinates
print(f"x={x}, y={y}, z={z}")

# Extended unpacking
first, *middle, last = (1, 2, 3, 4, 5)
print("first:", first)
print("middle:", middle)
print("last:", last)

# Swap variables elegantly
a, b = 10, 20
a, b = b, a
print(f"After swap: a={a}, b={b}")

# Single-element tuple
singleton = (42,)
print("Type:", type(singleton))

Tuple unpacking is one of Python's most elegant features. The starred expression (*middle) collects all 'remaining' elements into a list. Variable swapping without a temp variable is made possible by implicit tuple packing/unpacking.

Named Tuplespython
from collections import namedtuple

# Define a named tuple type
Employee = namedtuple("Employee", ["name", "department", "salary"])

# Create instances
emp1 = Employee("Alice", "Engineering", 95000)
emp2 = Employee("Bob", "Marketing", 72000)

# Access by name or index
print(emp1.name, emp1.department)
print(emp2[2])  # salary by index

# Named tuples are still immutable
try:
    emp1.salary = 100000
except AttributeError as e:
    print("Error:", e)

# Convert to dict
print(emp1._asdict())

namedtuple creates a lightweight class with named fields. Instances are immutable like regular tuples but far more readable. _asdict() converts to an OrderedDict for easy serialization.

Set Operationspython
python_devs  = {"Alice", "Bob", "Carol", "Dave"}
js_devs      = {"Bob", "Dave", "Eve", "Frank"}

# Union — all developers
all_devs = python_devs | js_devs
print("All devs:", sorted(all_devs))

# Intersection — know both languages
both = python_devs & js_devs
print("Know both:", sorted(both))

# Difference — Python only
python_only = python_devs - js_devs
print("Python only:", sorted(python_only))

# Symmetric difference — know exactly one
one_lang = python_devs ^ js_devs
print("One language:", sorted(one_lang))

# Fast membership test
print("Alice in Python devs:", "Alice" in python_devs)

# Remove duplicates from a list
with_dupes = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(with_dupes))
print("Unique:", sorted(unique))

Set operations mirror mathematical set theory. Membership testing in a set is O(1) (constant time) versus O(n) for a list, making sets ideal for lookup-heavy code. Converting a list to a set is the quickest way to deduplicate.

Quick Quiz

1. How do you create an empty set in Python?

2. What does the & operator do when applied to two sets?

3. Which of the following is a valid single-element tuple?

4. What makes frozenset different from set?

Was this lesson helpful?

PreviousNext