Python Basics — Tuple Methods

2 minute read

Tuple Methods

Since tuples are immutable, they only have two built-in methods: count() and index(). But tuples support many other operations through operators and built-in functions.

count() — Count Occurrences

numbers = (1, 2, 3, 2, 4, 2, 5)
print(numbers.count(2))  # 3
print(numbers.count(9))  # 0

index() — Find Position

colors = ("red", "green", "blue", "green")
print(colors.index("green"))  # 1 (first occurrence)
print(colors.index("blue"))   # 2

# ValueError if not found
# colors.index("yellow")  # ValueError: tuple.index(x): x not in tuple

With optional start and stop:

numbers = (10, 20, 30, 20, 40)
print(numbers.index(20))      # 1 (first occurrence)
print(numbers.index(20, 2))   # 3 (search from index 2)

Tuple Concatenation

a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print(c)  # (1, 2, 3, 4, 5, 6)

# Original tuples unchanged
print(a)  # (1, 2, 3)
print(b)  # (4, 5, 6)

Tuple Repetition

t = (0,) * 5
print(t)  # (0, 0, 0, 0, 0)

pattern = (1, 2) * 3
print(pattern)  # (1, 2, 1, 2, 1, 2)

Membership Testing

fruits = ("apple", "banana", "cherry")

print("banana" in fruits)     # True
print("grape" in fruits)      # False
print("grape" not in fruits)  # True

Tuple as Dictionary Key

Since tuples are immutable and hashable, they can be used as dictionary keys:

# Grid coordinates as keys
grid = {}
grid[(0, 0)] = "start"
grid[(1, 2)] = "treasure"
grid[(3, 3)] = "end"

print(grid[(1, 2)])  # treasure
# Counting pairs
edges = [("A", "B"), ("B", "C"), ("A", "B"), ("C", "D"), ("A", "B")]
edge_count = {}
for edge in edges:
    edge_count[edge] = edge_count.get(edge, 0) + 1

print(edge_count)
# {('A', 'B'): 3, ('B', 'C'): 1, ('C', 'D'): 1}

Lists cannot be dictionary keys because they are mutable.

Tuple Hashing

t = (1, 2, 3)
print(hash(t))  # e.g., 529344067295497451

# Tuples containing mutable elements are NOT hashable
mixed = (1, [2, 3])
# hash(mixed)  # TypeError: unhashable type: 'list'

Tuple Comparison

Tuples compare element by element (lexicographic order):

print((1, 2, 3) < (1, 2, 4))   # True (3 < 4)
print((1, 2) < (1, 2, 0))      # True (shorter tuple)
print((1, 3) > (1, 2))         # True (3 > 2)
print((1, 2, 3) == (1, 2, 3))  # True

This makes tuples sortable:

students = [("Charlie", 85), ("Alice", 95), ("Bob", 87)]
students.sort()  # Sorts by first element, then second
print(students)
# [('Alice', 95), ('Bob', 87), ('Charlie', 85)]

Built-in Functions with Tuples

numbers = (5, 2, 8, 1, 9, 3)

print(len(numbers))     # 6
print(min(numbers))     # 1
print(max(numbers))     # 9
print(sum(numbers))     # 28
print(sorted(numbers))  # [1, 2, 3, 5, 8, 9]  (returns a list!)
print(any(numbers))     # True (at least one truthy)
print(all(numbers))     # True (all truthy)

Complete Reference

Operation Syntax Returns
Count t.count(x) Number of occurrences
Index t.index(x) First index of x
Length len(t) Number of elements
Min / Max min(t) / max(t) Smallest / largest
Sum sum(t) Total (numeric only)
Sorted sorted(t) New sorted list
Concatenate t1 + t2 New tuple
Repeat t * n New tuple
Membership x in t True / False
Hash hash(t) Integer hash

Summary

  • Tuples have only two methods: count() and index()
  • Concatenation (+) and repetition (*) create new tuples
  • Tuples are hashable (if all elements are hashable)
  • Tuples can be dictionary keys — lists cannot
  • Tuples compare lexicographically
  • sorted() returns a list, not a tuple

Next up: Named Tuples →

Updated: