Tuples are similar to lists, but there's one important difference: tuples are immutable, which means you cannot change their items after creating them.
Let's understand how they work and why we use them.
What Are Tuples?
A tuple is an ordered collection of items that lets you store multiple values in a single variable.
Just like lists, tuples:
- Maintain the order of their items.
- Allow duplicate values.
- Can contain items of different data types.
- Support indexing and slicing.
But unlike lists, tuples are immutable. Once created, you cannot add, remove, or replace their items directly.
Creating Tuples
Tuples are usually created using round brackets (), with items separated by commas.
tuple1 = (1, 2, 36, 3, 15)
tuple2 = ("Red", "Yellow", "Blue")
tuple3 = (1, "John", 12, 5.3)
print(tuple1)
print(tuple2)
print(tuple3)
# Output:
# (1, 2, 36, 3, 15)
# ('Red', 'Yellow', 'Blue')
# (1, 'John', 12, 5.3)As you can see, a tuple can contain integers, strings, floats, or a combination of different data types.
Creating an Empty Tuple
You can create an empty tuple using either empty parentheses or the tuple() function.
empty_tuple1 = ()
empty_tuple2 = tuple()
print(empty_tuple1)
print(empty_tuple2)
# Output:
# ()
# ()Creating a Tuple Without Parentheses
Here's something interesting: parentheses are often optional when creating tuples.
The commas are what actually make a tuple.
point = 3, 5
print(point)
print(type(point))
# Output:
# (3, 5)
# <class 'tuple'>Creating a Tuple using tuple()
You can also create a tuple using Python's built-in tuple() function.
numbers = tuple([1, 2, 3])
print(numbers)
# Output:
# (1, 2, 3)Here, we're converting a list into a tuple.
You can use tuple() with other iterables, too. For example, strings are iterable, so Python creates a tuple containing each character separately.
letters = tuple("abc")
print(letters)
# Output:
# ('a', 'b', 'c')This is similar to how we worked with strings.
Creating a Single-item Tuple
There's one important thing to remember when creating a tuple with only one item.
You must add a comma after the item. Without the comma, Python treats the value as an ordinary value inside parentheses, not as a tuple.
tuple1 = (1)
print(type(tuple1))
# Output:
# <class 'int'>Now, let's add a comma.
tuple2 = (1,)
print(type(tuple2))
# Output:
# <class 'tuple'>The comma is what makes it a tuple, not the parentheses.
Why Use Tuples?
You might be wondering: if lists can store multiple values and are easier to modify, why do we need tuples?
Tuples are useful when you have values that belong together and shouldn't change.
For example:
Coordinates:
point = (3, 5)RGB colors:
color = (255, 0, 128)Function return values:
def get_user():
return "Shefali", 27
user = get_user()
print(user)
# Output:
# ('Shefali', 27)Remember we learned about the return statement? Returning multiple comma-separated values creates a tuple.
Tuples also appeared when we learned about *args. Python collects the extra positional arguments into a tuple.
def show_numbers(*args):
print(args)
print(type(args))
show_numbers(10, 20, 30)
# Output:
# (10, 20, 30)
# <class 'tuple'>Using a tuple communicates that the collection is not meant to be changed.
Tuples can also be slightly more memory-efficient than lists for similar data, although you generally choose them because of their meaning and immutability, not for performance alone.
Finding the Length of a Tuple
You can use Python's built-in len() function to find the number of items in a tuple.
numbers = (1, 2, 36, 3, 15)
length = len(numbers)
print(length)
# Output:
# 5Here, the tuple contains five items, so len() returns 5.
Accessing Tuple Items
Just like lists, you can access tuple items using indexing.
Each item has a position called an index.
Remember, Python indexing starts from 0:
- The first item has index
0. - The second item has index
1. - The third item has index
2.
For example:
fruits = ("Orange", "Apple", "Banana")
print(fruits[0])
print(fruits[1])
print(fruits[2])
# Output:
# Orange
# Apple
# BananaNegative Indexing
You can also access tuple items from the end using negative indexes.
-1refers to the last item.-2refers to the second-to-last item.-3refers to the third-to-last item.
fruits = ("Orange", "Apple", "Banana")
print(fruits[-1])
print(fruits[-2])
print(fruits[-3])
# Output:
# Banana
# Apple
# OrangeFor example, fruits[-3] is equivalent to fruits[len(fruits) - 3].
Checking If an Item Exists in a Tuple
You can use the in keyword to check whether a particular item exists in a tuple.
It returns True if the item is present and False if it isn't.
Example 1:
fruits = ("Orange", "Apple", "Banana")
if "Orange" in fruits:
print("Orange is in the tuple.")
else:
print("Orange is not in the tuple.")
# Output:
# Orange is in the tuple.Example 2:
numbers = (1, 57, 13)
if 7 in numbers:
print("7 is in the tuple.")
else:
print("7 is not in the tuple.")
# Output:
# 7 is not in the tuple.This is useful when you want to check whether a value exists before working with it.
Slicing Tuples
Just like lists, you can get a range of items from a tuple using slicing.
The slicing syntax is:
tuple_name[start:end:step]Here's what each part means:
start: The index where slicing begins.end: The index where slicing stops (not included).step: How many positions to move between selected items.
The step value is optional.
Let's look at a few examples.
Example 1: Getting Items Within a Range
numbers = (1, 57, 13, 6, 18, 54)
# Using positive indexes
print(numbers[2:5])
# Using negative indexes
print(numbers[-5:-2])
# Output:
# (13, 6, 18)
# (57, 13, 6)In the first example, numbers[2:5] starts at index 2 and stops before index 5.
In the second example, numbers[-5:-2] uses negative indexes to select a different range.
Example 2: Slicing Without an End Index
If you don't provide an end index, Python selects all items from the starting position to the end of the tuple.
numbers = (1, 57, 13, 6, 18, 54)
# Using positive indexes
print(numbers[2:])
# Using negative indexes
print(numbers[-5:])
# Output:
# (13, 6, 18, 54)
# (57, 13, 6, 18, 54)Example 3: Slicing Without a Start Index
If you don't provide a start index, Python starts from the beginning of the tuple and selects items up to the given end index.
numbers = (1, 57, 13, 6, 18, 54)
# Using positive indexes
print(numbers[:4])
# Using negative indexes
print(numbers[:-2])
# Output:
# (1, 57, 13, 6)
# (1, 57, 13, 6)Example 4: Skipping Items with Step
You can use the step value to skip items while slicing.
For example, a step of 2 selects every second item.
numbers = (1, 57, 13, 6, 18, 54)
# Select every second item
print(numbers[::2])
# Start from the second-last item and move forward
print(numbers[-2::2])
# Output:
# (1, 13, 18)
# (18,)Notice that the second result is (18,), which is a single-item tuple. The comma is important.
Tuple Unpacking
Tuple unpacking lets you assign tuple items to separate variables.
For example:
point = (3, 5)
x, y = point
print(x, y)
# Output:
# 3 5Here, Python assigns the first item to x and the second item to y.
You might remember doing something similar when we learned about multiple variable assignment.
For example:
x, y, z = 10, "Hello", [1, 2, 3]
print(x)
print(y)
print(z)
# Output:
# 10
# Hello
# [1, 2, 3]The comma-separated values on the right form a tuple, even though we didn't write parentheses.
You can also use unpacking to swap two variables.
a = 10
b = 20
a, b = b, a
print(a, b)
# Output:
# 20 10Python evaluates the values on the right and then assigns them to the variables on the left.
One thing to remember: the number of variables on the left should match the number of items being unpacked.
point = (3, 5)
x, y, z = point
# ValueError: not enough values to unpackHere, we have two values but three variables, so Python raises a ValueError.
Manipulating Tuples
Remember, tuples are immutable. This means you cannot directly add, remove, or change their items after creation.
For example, trying to change an item raises a TypeError.
fruits = ("Apple", "Orange", "Banana")
fruits[1] = "Mango"
# TypeError: 'tuple' object does not support item assignmentYou also cannot use list methods like append() to add items.
fruits = ("Apple", "Orange")
fruits.append("Mango")
# AttributeError: 'tuple' object has no attribute 'append'This is why tuples have only two built-in methods: count() and index(), which we'll explore shortly.
But There's One Interesting Detail
Immutable doesn't mean everything inside a tuple is frozen.
A tuple can contain a mutable object, such as a list. You cannot replace that list inside the tuple, but you can still modify the list itself.
data = ([1, 2], 3)
data[0].append(99)
print(data)
# Output:
# ([1, 2, 99], 3)The tuple still holds the same list. Only the list's contents changed.
A tuple containing only numbers and strings is fully fixed in this way, but a tuple containing a list can still reflect changes made to that list.
Converting a Tuple into a List
What if you really need to modify a tuple?
You can convert it into a list, make the changes, and convert it back into a tuple.
fruits = ("Apple", "Orange", "Plum", "Banana")
# Convert tuple to list
fruits_list = list(fruits)
# Add a new item
fruits_list.append("Guava")
# Convert list back to tuple
fruits = tuple(fruits_list)
print(fruits)
# Output:
# ('Apple', 'Orange', 'Plum', 'Banana', 'Guava')This creates a new tuple with the updated items. It doesn't change the original tuple.
If you need to add, remove, or update items frequently, a list is usually the better choice.
Concatenating Tuples
You can combine two or more tuples using the + operator.
This is called concatenation.
fruits1 = ("Apple", "Orange", "Plum")
fruits2 = ("Banana", "Grapes")
fruits = fruits1 + fruits2
print(fruits)
# Output:
# ('Apple', 'Orange', 'Plum', 'Banana', 'Grapes')The + operator creates a new tuple containing the items from both tuples. The original tuples remain unchanged.
Remember: Both sides must be tuples when using + to concatenate tuples.
numbers = (1, 2)
numbers = numbers + [3]
# TypeError: can only concatenate tuple (not "list") to tupleRepeating a Tuple
You can also use the * operator to repeat the items in a tuple.
numbers = (1, 2)
print(numbers * 2)
# Output:
# (1, 2, 1, 2)Using += with Tuples
You may remember using += with lists.
With tuples, += creates a new tuple and reassigns the variable to it. It doesn't modify the existing tuple.
numbers = (1, 2)
numbers += (3, 4)
print(numbers)
# Output:
# (1, 2, 3, 4)The original tuple object remains unchanged.
Tuple Methods
Tuples have only two built-in methods:
count()index()
Let's understand both.
count()
The count() method returns how many times a particular item appears in a tuple.
Syntax:
tuple_name.count(item)For example:
numbers = (1, 57, 3, 6, 18, 3, 3)
count_3 = numbers.count(3)
print(count_3)
# Output:
# 3Here, 3 appears three times, so count() returns 3.
index()
The index() method returns the index of the first occurrence of a given item.
Syntax:
tuple_name.index(item)For example:
numbers = (1, 57, 3, 6, 18, 54, 3)
number_index = numbers.index(3)
print("Index of 3 in numbers is:", number_index)
# Output:
# Index of 3 in numbers is: 2Here, the first occurrence of 3 is at index 2, so that's what index() returns.
If the item doesn't exist in the tuple, index() raises a ValueError.
You can also specify a starting position for the search.
numbers = (1, 57, 13, 6, 18, 54, 13)
number_index = numbers.index(13, 3)
print(number_index)
# Output:
# 6Here, the search starts at index 3, so Python finds the next occurrence of 13 at index 6.
Looping Through a Tuple
Just like lists, you can use a for loop to go through each item in a tuple.
fruits = ("Apple", "Banana", "Cherry")
for fruit in fruits:
print(fruit)
# Output:
# Apple
# Banana
# CherryThe loop works the same way as it did with lists.
Sorting a Tuple
Tuples don't have a sort() method because they are immutable.
But you can use the built-in sorted() function to get a sorted version of a tuple's items.
Remember, sorted() returns a list, not a tuple.
numbers = (3, 1, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers)
print(type(sorted_numbers))
# Output:
# [1, 2, 3]
# <class 'list'>If you need the result as a tuple, you can convert it back:
numbers = (3, 1, 2)
sorted_numbers = tuple(sorted(numbers))
print(sorted_numbers)
# Output:
# (1, 2, 3)👉 Next tutorial: Python Sets