githubEdit

Tuples

Tuples are ordered and immutable collections. They are similar to lists, but you cannot change their contents after creation.

Creating Tuples

empty = ()
numbers = (1, 2, 3)
mixed = (1, "a", 2.5)

packed = "cat", "dog", "rabbit"
cat, dog, rabbit = packed

Single-item tuples need a trailing comma:

single = (1,)

Accessing Items

t = (10, 20, 30, 40)

print(t[0])   # 10
print(t[-1])  # 40
print(t[1:3]) # (20, 30)

Immutability

If a tuple contains a mutable object (like a list), that inner object can be changed:

Common Methods

Membership and Iteration

When to Use Tuples

  • Fixed collections that should not change.

  • Keys in dictionaries (tuples are hashable if they contain only immutable items).

Next | Previous

Last updated