Python Tuple Operations
Table of Contents
In the last lesson, we learned about Python Introduction to Tuples. Now let’s join, repeat, search, and loop through tuples.
Let’s Do Things with Tuples
We know how to create a tuple. We know how to access items. We know that tuples are immutable.
But what can we actually do with them? What operations work on tuples?
Quite a lot, actually. We can join them. Repeat them. Check if something is inside. Find the smallest or largest. Count items. Find positions. And more.
Let’s go through the common tuple operations.
Joining Tuples with + in Python
We can join two tuples using the + operator. This is called concatenation.
tuple1 = (1, 2, 3)tuple2 = (4, 5, 6)combined = tuple1 + tuple2print(combined)Output
(1, 2, 3, 4, 5, 6)It creates a new tuple with all the items from both tuples. The original tuples are not changed. Because tuples are immutable.
We can also use += to add to an existing variable.
tuple1 = (1, 2, 3)tuple1 += (4, 5)print(tuple1)Output
(1, 2, 3, 4, 5)This creates a new tuple and assigns it to tuple1. The old tuple is discarded.
Repeating a Tuple with * in Python
We can repeat a tuple using the * operator.
numbers = (1, 2)repeated = numbers * 3print(repeated)Output
(1, 2, 1, 2, 1, 2)It repeats the tuple the given number of times. Again, it creates a new tuple.
This is useful when we want to initialize a tuple with the same value multiple times.
zeros = (0,) * 5print(zeros)Output
(0, 0, 0, 0, 0)But let’s be careful with mutable items. Tuples can contain lists, and repeating will share the same list reference. But that is an advanced topic. For now, let’s just know it works for simple values.
Checking Membership with in
We can check if an item is in a tuple using in.
colors = ("red", "green", "blue")print("green" in colors)Output
Trueprint("yellow" in colors)Output
FalseWe can also use not in.
print("yellow" not in colors)Output
TrueLooping Through a Python Tuple
We can loop through a tuple just like a list.
colors = ("red", "green", "blue")for color in colors: print(color)Output
redgreenblueWe can also use enumerate() to get both index and value.
for index, color in enumerate(colors): print(f"{index}: {color}")Output
0: red1: green2: blueFinding the Length with len()
len() gives us the number of items in a tuple.
colors = ("red", "green", "blue")print(len(colors))Output
3Finding the Smallest and Largest in a Python Tuple
Python has built-in functions min() and max() for tuples of comparable items.
numbers = (5, 2, 9, 1, 7)print(min(numbers))print(max(numbers))Output
19They also work on strings, comparing alphabetically.
words = ("banana", "apple", "cherry")print(min(words))print(max(words))Output
applecherryAdding Up Numbers with sum()
sum() adds up all the numbers in a tuple.
numbers = (1, 2, 3, 4, 5)print(sum(numbers))Output
15It only works on numbers. If we try it on strings, we get an error.
Sorting with sorted() in Python
Tuples do not have a .sort() method. Because they are immutable. But we can use the built-in sorted() function. It returns a new list with the items sorted. The original tuple is unchanged.
numbers = (5, 2, 9, 1, 7)sorted_numbers = sorted(numbers)print(sorted_numbers)Output
[1, 2, 5, 7, 9]Notice the output is a list, not a tuple. If we want a sorted tuple, we can convert it.
sorted_tuple = tuple(sorted(numbers))print(sorted_tuple)Output
(1, 2, 5, 7, 9)We can also sort in reverse.
print(sorted(numbers, reverse=True))Output
[9, 7, 5, 2, 1]The count() Method in Python Tuples
Tuples have a count() method. It tells us how many times a value appears.
numbers = (1, 2, 2, 3, 2, 4)print(numbers.count(2))Output
3The index() Method in Python Tuples
Tuples have an index() method. It returns the index of the first occurrence of a value.
numbers = (1, 2, 3, 2, 4)print(numbers.index(2))Output
1If the value is not found, it raises a ValueError.
numbers.index(10) # Error!So let’s check before using if we are not sure.
What We Cannot Do with Python Tuples
Because tuples are immutable, we cannot:
- Add items with
append()orextend() - Remove items with
remove()orpop() - Sort in place with
sort() - Reverse in place with
reverse() - Change items with assignment
If we need any of these, we use a list instead. Or we convert the tuple to a list, make changes, and convert back.
t = (1, 2, 3)lst = list(t)lst.append(4)t = tuple(lst)print(t)Output
(1, 2, 3, 4)That is a common pattern.
Python Tuple Operations: A Real-Life Example
Let’s say we have a tuple of daily temperatures for a week. We want to find the highest, lowest, and average.
temperatures = (72, 75, 68, 70, 74, 78, 80)
print(f"Highest: {max(temperatures)}")print(f"Lowest: {min(temperatures)}")print(f"Average: {sum(temperatures) / len(temperatures):.1f}")print(f"Number of days: {len(temperatures)}")Output
Highest: 80Lowest: 68Average: 73.9Number of days: 7That is simple and clean.
Common Mistakes with Python Tuple Operations
Mistake 1: Trying to Change a Tuple
t = (1, 2, 3)t[0] = 10 # Error!Let’s remember, tuples are immutable. If we need to change it, we convert to a list.
Mistake 2: Using append() on a Tuple
t = (1, 2)t.append(3) # Error!Tuples do not have an append method. We use a list if we need to add items.
Mistake 3: Forgetting That sorted() Returns a List
t = (3, 1, 2)result = sorted(t)print(type(result))Output
<class 'list'>If we need a tuple, we convert it with tuple().
Mistake 4: Using index() Without Checking
t = (1, 2, 3)t.index(10) # Error!So what do we do? We check if the value exists first.
if 10 in t: print(t.index(10))Mistake 5: Confusing + and *
t1 = (1, 2)t2 = (3, 4)print(t1 + t2) # (1, 2, 3, 4)print(t1 * 2) # (1, 2, 1, 2)+ joins, * repeats.
Next, we will learn about Python Packing and Unpacking and move values into and out of tuples.