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.
Tuple Characteristics:
- 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
Additionally, tuples can be used as keys in dictionaries, as being immutable ensures that they will not change their value over time.
If you want to learn more about Tuples
check the Introduction to Programming Course read more
Creating a Tuple
Tuples in Python are defined using parentheses ()
.
In this example, my_tuple
is a tuple that contains 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 that starts at 0 (similar to how you access elements of a list).
For example, to access the first element of the tuple my_tuple
, you use index 0:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Result: 10
print(my_tuple[2]) # Result: 30
Unpacking Tuples
In Python, we can assign the elements of a tuple to individual variables in one 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 multiple 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 similar to lists.
my_tuple = (10, 20, 30)
for number in my_tuple:
print(number)