SyntaxStudy
Sign Up
Python Intermediate 9 min read

Tuples and Sets

Tuples and Sets

Tuples

Ordered, immutable sequences.

point = (3, 4)
x, y = point  # unpacking
coords = (1,)  # single-element tuple

# Named tuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)

Sets

Unordered collections with unique elements.

s = {1, 2, 3, 3, 2}  # {1, 2, 3}
s.add(4)
s.discard(1)

a = {1,2,3}; b = {2,3,4}
print(a | b)  # union
print(a & b)  # intersection
print(a - b)  # difference
Pro Tip

Sets use hashing — membership check x in s is O(1).