Cómo comprobar si una tupla tiene una longitud determinada en Python

PythonPythonBeginner
Practicar Ahora

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este laboratorio, aprenderás cómo verificar si una tupla tiene una longitud determinada en Python. Esto implica comprender las tuplas como secuencias ordenadas e inmutables y utilizar la función incorporada len() para determinar el número de elementos dentro de una tupla.

Crearás un script de Python llamado tuple_length.py para definir tuplas, calcular sus longitudes utilizando len() e imprimir los resultados. El laboratorio demuestra esto tanto con tuplas de enteros como con tuplas que contienen tipos de datos mixtos, mostrando la versatilidad de la función len().


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559587{{"Cómo comprobar si una tupla tiene una longitud determinada en Python"}} python/tuples -.-> lab-559587{{"Cómo comprobar si una tupla tiene una longitud determinada en Python"}} python/build_in_functions -.-> lab-559587{{"Cómo comprobar si una tupla tiene una longitud determinada en Python"}} python/data_collections -.-> lab-559587{{"Cómo comprobar si una tupla tiene una longitud determinada en Python"}} end

Comprender la longitud de una tupla

En este paso, aprenderás sobre las tuplas y cómo determinar su longitud utilizando la función len() en Python. Las tuplas son una estructura de datos fundamental en Python, similares a las listas, pero con una diferencia clave: son inmutables, lo que significa que sus elementos no se pueden cambiar después de su creación. Comprender cómo trabajar con tuplas es esencial para cualquier programador de Python.

Una tupla es una secuencia ordenada de elementos. Las tuplas se escriben con paréntesis redondos. Por ejemplo:

my_tuple = (1, 2, 3, "hello")

Para encontrar el número de elementos en una tupla, puedes utilizar la función incorporada len(). Veamos cómo funciona.

  1. Abre tu editor de VS Code.

  2. Crea un nuevo archivo llamado tuple_length.py en tu directorio ~/project.

    touch ~/project/tuple_length.py
  3. Abre el archivo tuple_length.py en el editor y agrega el siguiente código de Python:

    my_tuple = (10, 20, 30, 40, 50)
    length = len(my_tuple)
    print("The length of the tuple is:", length)

    Este código primero define una tupla llamada my_tuple que contiene cinco elementos enteros. Luego, utiliza la función len() para calcular el número de elementos en la tupla y almacena el resultado en la variable length. Finalmente, imprime la longitud de la tupla en la consola.

  4. Ejecuta el script de Python utilizando el siguiente comando en la terminal:

    python ~/project/tuple_length.py

    Deberías ver la siguiente salida:

    The length of the tuple is: 5

    Esta salida confirma que la función len() determinó correctamente el número de elementos en la tupla.

  5. Ahora, probemos con una tupla diferente que contenga tipos de datos mixtos:

    mixed_tuple = (1, "hello", 3.14, True)
    length = len(mixed_tuple)
    print("The length of the mixed tuple is:", length)

    Agrega este código a tu archivo tuple_length.py, de modo que el archivo completo se vea así:

    my_tuple = (10, 20, 30, 40, 50)
    length = len(my_tuple)
    print("The length of the tuple is:", length)
    
    mixed_tuple = (1, "hello", 3.14, True)
    length = len(mixed_tuple)
    print("The length of the mixed tuple is:", length)
  6. Ejecuta el script nuevamente:

    python ~/project/tuple_length.py

    Deberías ver la siguiente salida:

    The length of the tuple is: 5
    The length of the mixed tuple is: 4

    Como puedes ver, la función len() funciona correctamente con tuplas que contienen diferentes tipos de datos.

Utilizar la función len()

En el paso anterior, aprendiste cómo determinar la longitud de una tupla utilizando la función len(). Ahora, exploremos aplicaciones más prácticas de esta función. Aprenderás cómo usar la función len() con diferentes tipos de tuplas y cómo almacenar el resultado para su posterior uso en tu programa.

  1. Abre tu editor de VS Code y abre el archivo tuple_length.py en tu directorio ~/project.

  2. Modifica el archivo tuple_length.py para incluir el siguiente código:

    ## Tuple of strings
    string_tuple = ("apple", "banana", "cherry")
    string_length = len(string_tuple)
    print("The length of the string tuple is:", string_length)
    
    ## Tuple of mixed data types
    mixed_tuple = (1, "hello", 3.14, True)
    mixed_length = len(mixed_tuple)
    print("The length of the mixed tuple is:", mixed_length)
    
    ## Empty tuple
    empty_tuple = ()
    empty_length = len(empty_tuple)
    print("The length of the empty tuple is:", empty_length)

    En este código, estamos calculando la longitud de tres tuplas diferentes: string_tuple, mixed_tuple y empty_tuple. Las longitudes se almacenan en las variables string_length, mixed_length y empty_length, respectivamente, y luego se imprimen en la consola.

  3. Ejecuta el script de Python utilizando el siguiente comando en la terminal:

    python ~/project/tuple_length.py

    Deberías ver la siguiente salida:

    The length of the string tuple is: 3
    The length of the mixed tuple is: 4
    The length of the empty tuple is: 0

    Esta salida demuestra que la función len() se puede utilizar con tuplas que contienen cadenas, tipos de datos mixtos e incluso tuplas vacías.

  4. Ahora, veamos cómo puedes utilizar la longitud de una tupla en una declaración condicional. Agrega el siguiente código a tu archivo tuple_length.py:

    ## Tuple of numbers
    number_tuple = (1, 2, 3, 4, 5)
    number_length = len(number_tuple)
    
    if number_length > 3:
        print("The tuple has more than 3 elements.")
    else:
        print("The tuple has 3 or fewer elements.")

    Este código verifica si la longitud de la tupla number_tuple es mayor que 3. Si es así, imprime "The tuple has more than 3 elements." De lo contrario, imprime "The tuple has 3 or fewer elements."

    El archivo tuple_length.py completo ahora debería verse así:

    ## Tuple of strings
    string_tuple = ("apple", "banana", "cherry")
    string_length = len(string_tuple)
    print("The length of the string tuple is:", string_length)
    
    ## Tuple of mixed data types
    mixed_tuple = (1, "hello", 3.14, True)
    mixed_length = len(mixed_tuple)
    print("The length of the mixed tuple is:", mixed_length)
    
    ## Empty tuple
    empty_tuple = ()
    empty_length = len(empty_tuple)
    print("The length of the empty tuple is:", empty_length)
    
    ## Tuple of numbers
    number_tuple = (1, 2, 3, 4, 5)
    number_length = len(number_tuple)
    
    if number_length > 3:
        print("The tuple has more than 3 elements.")
    else:
        print("The tuple has 3 or fewer elements.")
  5. Ejecuta el script nuevamente:

    python ~/project/tuple_length.py

    Deberías ver la siguiente salida:

    The length of the string tuple is: 3
    The length of the mixed tuple is: 4
    The length of the empty tuple is: 0
    The tuple has more than 3 elements.

    Esta salida demuestra cómo puedes utilizar la función len() para obtener la longitud de una tupla y luego utilizar esa longitud en una declaración condicional para controlar el flujo de tu programa.

Comparar con la longitud deseada

En este paso, aprenderás cómo comparar la longitud de una tupla con una longitud deseada. Esta es una tarea común en la programación, especialmente cuando necesitas validar datos o asegurarte de que una tupla cumpla con ciertos requisitos.

  1. Abre tu editor de VS Code y abre el archivo tuple_length.py en tu directorio ~/project.

  2. Modifica el archivo tuple_length.py para incluir el siguiente código:

    def check_tuple_length(my_tuple, desired_length):
        """
        Checks if the length of a tuple matches the desired length.
        """
        if len(my_tuple) == desired_length:
            print("The tuple has the desired length.")
        else:
            print("The tuple does not have the desired length.")
    
    ## Example usage:
    my_tuple = (1, 2, 3)
    desired_length = 3
    check_tuple_length(my_tuple, desired_length)
    
    another_tuple = ("a", "b", "c", "d")
    desired_length = 3
    check_tuple_length(another_tuple, desired_length)

    En este código, definimos una función llamada check_tuple_length que toma dos argumentos: una tupla (my_tuple) y una longitud deseada (desired_length). La función utiliza la función len() para obtener la longitud de la tupla y luego la compara con la longitud deseada. Si las longitudes coinciden, imprime "The tuple has the desired length." De lo contrario, imprime "The tuple does not have the desired length."

    Luego proporcionamos dos ejemplos de cómo usar la función. En el primer ejemplo, creamos una tupla my_tuple con tres elementos y establecemos la desired_length en 3. En el segundo ejemplo, creamos una tupla another_tuple con cuatro elementos y establecemos la desired_length en 3.

    El archivo tuple_length.py completo ahora debería verse así:

    ## Tuple of strings
    string_tuple = ("apple", "banana", "cherry")
    string_length = len(string_tuple)
    print("The length of the string tuple is:", string_length)
    
    ## Tuple of mixed data types
    mixed_tuple = (1, "hello", 3.14, True)
    mixed_length = len(mixed_tuple)
    print("The length of the mixed tuple is:", mixed_length)
    
    ## Empty tuple
    empty_tuple = ()
    empty_length = len(empty_tuple)
    print("The length of the empty tuple is:", empty_length)
    
    ## Tuple of numbers
    number_tuple = (1, 2, 3, 4, 5)
    number_length = len(number_tuple)
    
    if number_length > 3:
        print("The tuple has more than 3 elements.")
    else:
        print("The tuple has 3 or fewer elements.")
    
    def check_tuple_length(my_tuple, desired_length):
        """
        Checks if the length of a tuple matches the desired length.
        """
        if len(my_tuple) == desired_length:
            print("The tuple has the desired length.")
        else:
            print("The tuple does not have the desired length.")
    
    ## Example usage:
    my_tuple = (1, 2, 3)
    desired_length = 3
    check_tuple_length(my_tuple, desired_length)
    
    another_tuple = ("a", "b", "c", "d")
    desired_length = 3
    check_tuple_length(another_tuple, desired_length)
  3. Ejecuta el script nuevamente:

    python ~/project/tuple_length.py

    Deberías ver la siguiente salida:

    The length of the string tuple is: 3
    The length of the mixed tuple is: 4
    The length of the empty tuple is: 0
    The tuple has more than 3 elements.
    The tuple has the desired length.
    The tuple does not have the desired length.

    Esta salida demuestra cómo puedes usar la función len() para comparar la longitud de una tupla con una longitud deseada y tomar diferentes acciones según el resultado.

Resumen

En este laboratorio, aprendiste sobre las tuplas, que son secuencias ordenadas e inmutables de elementos en Python, similares a las listas pero inalterables. Utilizaste la función len() para determinar el número de elementos en una tupla, demostrando su aplicación tanto con tuplas de enteros como de tipos de datos mixtos.

El laboratorio implicó crear un script de Python llamado tuple_length.py, definir tuplas, calcular sus longitudes utilizando len() e imprimir los resultados en la consola. Este proceso reforzó la comprensión de cómo trabajar eficazmente con tuplas y determinar su tamaño en Python.