Python Sets & Tuples

Working with sets and tuples - immutable and unordered data structures in Python.

Sets Basics

# Create set
numbers = {1, 2, 3, 4, 5}
empty_set = set()  # {} creates dict, not set
from_list = set([1, 2, 2, 3, 3])  # {1, 2, 3} - removes duplicates

# Add & remove
numbers.add(6)  # add single item
numbers.remove(3)  # remove (raises error if not found)
numbers.discard(3)  # remove (no error if not found)
numbers.pop()  # remove and return arbitrary item
numbers.clear()  # remove all items

Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union (all elements)
a | b  # {1, 2, 3, 4, 5, 6}
a.union(b)  # same as above

# Intersection (common elements)
a & b  # {3, 4}
a.intersection(b)  # same as above

# Difference (in a but not in b)
a - b  # {1, 2}
a.difference(b)  # same as above

# Symmetric difference (in a or b but not both)
a ^ b  # {1, 2, 5, 6}
a.symmetric_difference(b)  # same

Set Methods

a = {1, 2, 3}
b = {1, 2, 3, 4, 5}

# Check membership
2 in a  # True
5 not in a  # True

# Subset & superset
a.issubset(b)  # True (all elements of a are in b)
b.issuperset(a)  # True (b contains all elements of a)
a.isdisjoint(b)  # False (have common elements)

# Copy
c = a.copy()  # shallow copy

Tuples Basics

# Create tuple
point = (10, 20)
single = (42,)  # comma needed for single item
colors = 'red', 'green', 'blue'  # parentheses optional

# Access elements
point[0]  # 10
point[-1]  # 20

# Tuples are immutable
# point[0] = 15  # ERROR! Cannot modify

# Tuple unpacking
x, y = point  # x=10, y=20
a, b, c = colors  # a='red', b='green', c='blue'

Tuple Methods

numbers = (1, 2, 2, 3, 3, 3, 4)

# Count occurrences
numbers.count(3)  # 3
numbers.count(1)  # 1

# Find index
numbers.index(3)  # 3 (first occurrence)

# Length
len(numbers)  # 7

# Concatenation
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2  # (1, 2, 3, 4)

# Repetition
t = (1, 2) * 3  # (1, 2, 1, 2, 1, 2)