Skip to content

Python Tuples

A tuple is an ordered, immutable sequence of Python objects. ‘Immutable’ means that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are similar to lists, but the key difference is their immutability.

Tuples are defined by enclosing comma-separated values within parentheses (). Parentheses are optional if the context is clear, but using them is standard practice.

# Creating tuples
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5)
tuple3 = "a", "b", "c", "d" # Parentheses optional here
empty_tuple = ()
# Tuple with a single element requires a trailing comma
single_element_tuple = (50,)
not_a_tuple = (50) # This is just the integer 50
print(type(single_element_tuple)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'int'>

Like lists and strings, tuple elements are indexed starting from 0. You can access elements, slice them, concatenate tuples, and repeat them.

Use square brackets [] with the index to access individual elements, or slicing [start:end:step] to get sub-tuples.

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print(f"tup1[0]: {tup1[0]}") # Access first element
print(f"tup2[1:5]: {tup2[1:5]}") # Slice from index 1 up to (not including) 5
print(f"tup1[-1]: {tup1[-1]}") # Access last element

Output:

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
tup1[-1]: 2000

Tuples are immutable. You cannot change an element within a tuple after it’s created.

tup1 = (12, 34.56)
# The following action is INVALID and will raise a TypeError:
# tup1[0] = 100
# TypeError: 'tuple' object does not support item assignment

However, you can create new tuples by combining existing tuples or parts of them.

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Create a new tuple by concatenating tup1 and tup2
tup3 = tup1 + tup2
print(f"New tuple tup3: {tup3}")

Output:

New tuple tup3: (12, 34.56, 'abc', 'xyz')

If a tuple contains a mutable object (like a list), the contents of that mutable object can be changed, but the object itself remains at the same position within the tuple.

tuple_with_list = (1, 2, ['a', 'b'])
print(f"Original: {tuple_with_list}")
# Modify the list inside the tuple (this is allowed)
tuple_with_list[2].append('c')
print(f"Modified: {tuple_with_list}")
# Attempting to replace the list object itself fails
# tuple_with_list[2] = ['x', 'y'] # TypeError!

Because tuples are immutable, you cannot remove individual elements from a tuple.

You can, however, delete an entire tuple object using the del statement.

tup = ('physics', 'chemistry', 1997, 2000)
print(f"Original tuple: {tup}")
# Delete the entire tuple object
del tup
# Attempting to access 'tup' now will raise a NameError
# print(tup)
# NameError: name 'tup' is not defined
print("Tuple 'tup' has been deleted.")

Tuples support standard sequence operations like concatenation (+) and repetition (*), which result in new tuples.

Python ExpressionResultDescription
len((1, 2, 3))3Length
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')Repetition
3 in (1, 2, 3)TrueMembership checking
for x in (1, 2, 3): print(x, end=' ')1 2 3 Iteration

Indexing and slicing work just like with lists and strings.

T = ('spam', 'Spam', 'SPAM!', 'eggs')
Python ExpressionResultDescription
T[0]'spam'First element (index 0)
T[-1]'eggs'Last element
T[1:3]('Spam', 'SPAM!')Slice from index 1 up to (not including) 3
T[::2]('spam', 'SPAM!')Every second element

A very common and powerful feature is tuple unpacking, where you assign the elements of a tuple to individual variables. The number of variables must match the number of elements in the tuple.

point = (10, 20, 30)
x, y, z = point # Unpacking
print(f"x = {x}, y = {y}, z = {z}")
# Can be used for easy swapping
a = 5
b = 10
a, b = b, a # Swap values using tuple packing/unpacking
print(f"Swapped: a = {a}, b = {b}")
# Extended unpacking (Python 3)
numbers = (1, 2, 3, 4, 5)
first, second, *rest = numbers
print(f"first: {first}, second: {second}, rest: {rest}")
first, *middle, last = numbers
print(f"first: {first}, middle: {middle}, last: {last}")

Output:

x = 10, y = 20, z = 30
Swapped: a = 10, b = 5
first: 1, second: 2, rest: [3, 4, 5]
first: 1, middle: [2, 3, 4], last: 5

Python includes functions that can operate on tuples:

FunctionDescription
len(tuple)Gives the total number of items in the tuple.
max(tuple)Returns the item from the tuple with the maximum value (items must be comparable).
min(tuple)Returns the item from the tuple with the minimum value (items must be comparable).
sum(tuple)Returns the sum of all items in the tuple (items must be numeric).
tuple(iterable)Converts an iterable (like a list, string, or range) into a tuple.
sorted(tuple)Returns a new list containing all items from the tuple in ascending order.

Note: The cmp(tuple1, tuple2) function from Python 2 is removed in Python 3. Use standard comparison operators (<, >, ==, etc.) which work lexicographically on tuples.

Despite their similarity to lists, tuples are useful in several scenarios: