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().
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.
Abre tu editor de VS Code.
Crea un nuevo archivo llamado
tuple_length.pyen tu directorio~/project.touch ~/project/tuple_length.pyAbre el archivo
tuple_length.pyen 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_tupleque contiene cinco elementos enteros. Luego, utiliza la funciónlen()para calcular el número de elementos en la tupla y almacena el resultado en la variablelength. Finalmente, imprime la longitud de la tupla en la consola.Ejecuta el script de Python utilizando el siguiente comando en la terminal:
python ~/project/tuple_length.pyDeberías ver la siguiente salida:
The length of the tuple is: 5Esta salida confirma que la función
len()determinó correctamente el número de elementos en la tupla.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)Ejecuta el script nuevamente:
python ~/project/tuple_length.pyDeberías ver la siguiente salida:
The length of the tuple is: 5 The length of the mixed tuple is: 4Como 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.
Abre tu editor de VS Code y abre el archivo
tuple_length.pyen tu directorio~/project.Modifica el archivo
tuple_length.pypara 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_tupleyempty_tuple. Las longitudes se almacenan en las variablesstring_length,mixed_lengthyempty_length, respectivamente, y luego se imprimen en la consola.Ejecuta el script de Python utilizando el siguiente comando en la terminal:
python ~/project/tuple_length.pyDeberí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: 0Esta salida demuestra que la función
len()se puede utilizar con tuplas que contienen cadenas, tipos de datos mixtos e incluso tuplas vacías.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_tuplees 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.pycompleto 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.")Ejecuta el script nuevamente:
python ~/project/tuple_length.pyDeberí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.
Abre tu editor de VS Code y abre el archivo
tuple_length.pyen tu directorio~/project.Modifica el archivo
tuple_length.pypara 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_lengthque toma dos argumentos: una tupla (my_tuple) y una longitud deseada (desired_length). La función utiliza la funciónlen()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_tuplecon tres elementos y establecemos ladesired_lengthen 3. En el segundo ejemplo, creamos una tuplaanother_tuplecon cuatro elementos y establecemos ladesired_lengthen 3.El archivo
tuple_length.pycompleto 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)Ejecuta el script nuevamente:
python ~/project/tuple_length.pyDeberí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.



