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 deleted.

Tuples are useful when you need to store a collection of elements that will not change over time.

In addition, tuples can be used as keys in dictionaries, since they are immutable, guaranteeing that their value will not change over time.

Characteristics of Tuples:

  • Immutability: Once created, their elements cannot be modified.
  • Ordered: The elements of a tuple are ordered and maintain the order in which they were added.
  • can contain any type of data: A tuple can contain elements of different data types, such as integers, strings, floats, or other tuples.

If you want to learn more
consult the Introduction to Programming Course read more

Creating a Tuple

Tuples 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)
my_other_tuple = tuple([1, 2, 3])

Common Operations with Tuples

Accessing Tuple Elements

To access the elements of a tuple, indexing is used, 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

Unpacking Tuples

In Python, we can assign the elements of a tuple to individual variables in a single step. This is called “unpacking tuples”.

my_tuple = ("Juan", "Perez", 30)
name, last_name, age = my_tuple
print(name)  # Result: Juan
print(last_name)  # Result: Perez
print(age)  # Result: 30

Common Uses of Tuples

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

  • Returning multiple values: When a function needs to return multiple values, it can use a tuple to do so in a clear way.

    def get_person_data():
        name = "Juan"
        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 = ("Juan", 30)
    person2 = ("Ana", 25)
    
    people_dictionary = {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)