Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 11

Tuples and sets

FreeLesson 13 of 78

A tuple is a list that cannot change. A set is a bag of unique items with no order. Each solves a problem a list handles badly.

TUPLES: FIXED RECORDSPYTHON 3.12
point = (12.97, 77.59)            # round brackets: a tuple
print(point[0], len(point))

lat, lon = point                  # unpacking
print(lat, lon)

def min_max(values):
    return min(values), max(values)   # returns a tuple
low, high = min_max([747, 3498, 1048])
print(low, high)

Output

12.97 2
12.97 77.59
747 3498
SETS: UNIQUE ITEMS AND FAST MEMBERSHIPPYTHON 3.12
statuses = ["delivered", "cancelled", "delivered",
            "returned", "delivered"]
unique = set(statuses)
print(unique, len(unique))

ids = {101, 102, 103}
ids.add(104)
ids.add(101)                       # already there: nothing happens
print(ids, 102 in ids)

yesterday = {101, 102, 103, 104}
today = {103, 104, 105}
print("new today:", today - yesterday)
print("in both:  ", today & yesterday)
print("all:      ", yesterday | today)

Output

{'delivered', 'returned', 'cancelled'} 3
{104, 101, 102, 103} True
new today: {105}
in both:   {104, 103}
all:       {101, 102, 103, 104, 105}
ListTupleSet
Brackets [1, 2](1, 2){1, 2}
Ordered, has positions YesYesNo
Can change YesNoYes (add/remove)
Duplicates AllowedAllowedRemoved automatically
Best for A sequence you editA fixed recordUniqueness and "is x in here?"

Try it yourself before moving on

  1. Unpack ("2025-04-20", 2397) into two variables and print them.
  2. Customers who ordered in January but not February: use set difference.
  3. How many unique cities are in ["Pune", "Delhi", "Pune", "Mumbai"]?