SyntaxStudy
Sign Up
Python Beginner 7 min read

Tuple Methods & Uses

Tuple Methods & Uses

Tuples have only two built-in methods, but they are very useful. Tuples shine as lightweight records and dictionary keys.

count() & index()

t = (1, 2, 3, 2, 4, 2, 5)
print(t.count(2))    # 3
print(t.index(3))    # 2 (first occurrence)
print(t.index(2))    # 1 (first occurrence)

Tuple vs List

import sys
lst = [1, 2, 3, 4, 5]
tup = (1, 2, 3, 4, 5)
print(sys.getsizeof(lst))  # larger
print(sys.getsizeof(tup))  # smaller

# Tuples are faster to iterate and unpack

Tuples as Dict Keys

# Lists cannot be dict keys (unhashable)
locations = {}
locations[(40.7128, -74.0060)] = "New York"
locations[(51.5074, -0.1278)]  = "London"
print(locations[(40.7128, -74.0060)])  # New York

Returning Multiple Values

def min_max(lst):
    return min(lst), max(lst)

lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(lo, hi)   # 1 9
Example
data = (5, 3, 8, 3, 1, 3)
print(data.count(3))  # 3
print(data.index(8))  # 2

def stats(nums):
    return min(nums), max(nums), sum(nums)/len(nums)

lo, hi, avg = stats([4, 7, 2, 9])
print(f"min={lo}, max={hi}, avg={avg}")
Pro Tip

Functions that return multiple values actually return a tuple. Python unpacks it automatically during assignment.