Tuples are a collection of ordered and immutable elements. This means that once a tuple is created, its elements cannot be modified, added, or removed.
Tuples are useful when you need to store a collection of elements that will not change over time.
Characteristics of Tuples:
- Immutability: Once created, its elements cannot be modified
- Ordered: The elements of a tuple are ordered and maintain the order in which they were added
- Can contain any data type: A tuple can contain elements of different data types
Furthermore, tuples can be used as keys in dictionaries, because being immutable, they guarantee that their value will not change over time.
If you want to learn more, check out the Introduction to Programming Course
Creating a tuple
Tuples in Python are defined using parentheses ().
In this example, my_tuple is a tuple containing the numbers from 1 to 5.
my_tuple = (1, 2, 3, 4, 5)
We can also use the tuple() function, for example to convert from a collection.
my_other_tuple = tuple([1, 2, 3])
Common operations with tuples
Accessing elements of a tuple
To access the elements of a tuple we can use a numeric index starting at 0 (similar to how elements of a list are accessed).
For example, to access the first element of the tuple my_tuple, index 0 is used:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Result: 10
print(my_tuple[2]) # Result: 30
Tuple unpacking
In Python, we can assign the elements of a tuple to individual variables in a single step (this is called “tuple unpacking”).
my_tuple = ("Luis", "Perez", 30)
name, surname, age = my_tuple
print(name) # Result: Luis
print(surname) # Result: Perez
print(age) # Result: 30
Practical examples
Tuples are useful in many situations. Let’s look at some examples.
Returning Multiple Values
When a function needs to return several values, it can use a tuple to do so clearly.
def get_person_data():
name = "Luis"
age = 30
return name, age
data = get_person_data()
name, age = data
Dictionary Keys
Tuples can be used as keys in a dictionary because they are immutable.
person1 = ("Luis", 30)
person2 = ("Ana", 25)
people_dict = {person1: "Programmer", person2: "Designer"}
Iteration
Tuples can be used in for loops similarly to lists.
my_tuple = (10, 20, 30)
for number in my_tuple:
print(number)
