python-tuplas

Tuples in Python

  • 3 min

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)
Copied!

We can also use the tuple() function, for example to convert from a collection.

my_other_tuple = tuple([1, 2, 3])
Copied!

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
Copied!

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
Copied!

Practical examples

Tuples are useful in many situations. Let’s look at some examples.