SyntaxStudy
Sign Up
Python Beginner 7 min read

Tuple Basics

Tuple Basics

Tuples are ordered, immutable sequences. Once created, their elements cannot be changed, added, or removed.

Creating Tuples

t1 = (1, 2, 3)
t2 = "a", "b", "c"   # parentheses optional
t3 = (42,)            # single-element (trailing comma!)
t4 = tuple([1, 2, 3]) # from list
empty = ()

Accessing Elements

coords = (10.5, 20.3, 5.0)
print(coords[0])    # 10.5
print(coords[-1])   # 5.0
print(coords[1:])   # (20.3, 5.0)

Unpacking

x, y, z = coords
print(x, y, z)

# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

Immutability

t = (1, 2, 3)
# t[0] = 99  # TypeError: 'tuple' does not support item assignment
# But if a tuple contains a list, the list IS mutable:
t2 = ([1, 2], [3, 4])
t2[0].append(3)   # works!
Example
point = (3, 7)
x, y = point
print(f"x={x}, y={y}")

rgb = (255, 128, 0)
print(rgb[0])   # 255
print(rgb[-1])  # 0
print(rgb[:2])  # (255, 128)
Pro Tip

A single-element tuple MUST have a trailing comma: (42,). Without it, (42) is just the integer 42 in parentheses.