Language: EN

python-tuplas

Tuples in Python

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.

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.