PY

Tuples & Sets

Python · 8 entries

Creating & Using Tuples

syntax
t = (val1, val2, ...)
t = val1, val2
example
point = (10, 20)
singleton = (42,)
x, y = point
print(f"x={x}, y={y}")
print(len(singleton))
output
x=10, y=20
1

Note A single-element tuple requires a trailing comma: (42,). Without it, (42) is just an integer in parentheses. Tuples are immutable.

Named Tuples

syntax
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
example
from collections import namedtuple

Color = namedtuple("Color", ["red", "green", "blue"])
sky = Color(135, 206, 235)
print(sky.red, sky.blue)
print(sky._asdict())
output
135 235
{'red': 135, 'green': 206, 'blue': 235}

Note Named tuples give readable field access while staying immutable. For mutable fields or defaults, consider dataclasses instead.

NamedTuple (typing-based)

syntax
from typing import NamedTuple
class Name(NamedTuple):
    field: type
example
from typing import NamedTuple

class Endpoint(NamedTuple):
    host: str
    port: int = 443

api = Endpoint("api.example.com")
print(api.host, api.port)
output
api.example.com 443

Note The class-based NamedTuple supports type annotations and default values, making it more modern than the functional namedtuple() form.

Creating Sets

syntax
s = {val1, val2, ...}
s = set(iterable)
example
tags = {"python", "tutorial", "beginner"}
from_list = set([1, 2, 2, 3, 3, 3])
print(from_list)

empty_set = set()
print(type(empty_set))
output
{1, 2, 3}
<class 'set'>

Note Use set() for an empty set, NOT {}. Empty braces {} create an empty dictionary, not a set.

Set Operations

syntax
a | b  (union)
a & b  (intersection)
a - b  (difference)
a ^ b  (symmetric difference)
example
frontend = {"alice", "bob", "carol"}
backend = {"bob", "carol", "dave"}

print(frontend | backend)
print(frontend & backend)
print(frontend - backend)
print(frontend ^ backend)
output
{'alice', 'bob', 'carol', 'dave'}
{'bob', 'carol'}
{'alice'}
{'alice', 'dave'}

Note Set operations are extremely fast (O(min(len(a), len(b))) for intersection). Use them instead of nested loops for membership checks.

frozenset (Immutable Set)

syntax
fs = frozenset(iterable)
example
permissions = frozenset(["read", "write"])
print("read" in permissions)

# Can be used as a dictionary key
cache = {permissions: "admin"}
print(cache[frozenset(["read", "write"])])
output
True
admin

Note frozenset is hashable, so it can be used as a dict key or as an element inside another set. Regular sets cannot.

Set Mutation Methods

syntax
s.add(elem)
s.discard(elem)
s.remove(elem)
example
active = {"alice", "bob"}
active.add("carol")
active.discard("bob")
active.discard("nonexistent")
print(active)
output
{'alice', 'carol'}

Note discard() silently ignores missing elements. remove() raises KeyError if the element is not found. Prefer discard() when absence is acceptable.