Usar la función len()
En el paso anterior, aprendiste cómo obtener el tamaño de un conjunto (set) utilizando la función len()
. En este paso, exploraremos formas más avanzadas de usar la función len()
con conjuntos, incluyendo su uso dentro de declaraciones condicionales y bucles.
Comencemos modificando nuestro script set_size.py
para incluir una declaración condicional que verifique si el conjunto está vacío. Abre tu archivo set_size.py
en el editor de VS Code y modifícalo de la siguiente manera:
## Create a set of numbers
my_set = {1, 2, 3, 4, 5}
## Print the set
print(my_set)
## Get the size of the set using the len() function
set_size = len(my_set)
## Print the size of the set
print("The size of the set is:", set_size)
## Check if the set is empty
if set_size == 0:
print("The set is empty.")
else:
print("The set is not empty.")
Guarda el archivo y ejecútalo:
python set_size.py
Deberías ver la siguiente salida:
{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.
Ahora, modifiquemos el script para crear un conjunto vacío y verificar su tamaño. Cambia la primera línea de tu script set_size.py
para crear un conjunto vacío:
## Create an empty set
my_set = set()
## Print the set
print(my_set)
## Get the size of the set using the len() function
set_size = len(my_set)
## Print the size of the set
print("The size of the set is:", set_size)
## Check if the set is empty
if set_size == 0:
print("The set is empty.")
else:
print("The set is not empty.")
Guarda el archivo y ejecútalo nuevamente:
python set_size.py
Esta vez, deberías ver la siguiente salida:
set()
The size of the set is: 0
The set is empty.
Como puedes ver, la función len()
devuelve 0 para un conjunto vacío, y nuestra declaración condicional identifica correctamente que el conjunto está vacío.
Ahora, usemos la función len()
en un bucle. Supongamos que queremos eliminar elementos de un conjunto hasta que esté vacío. Modifica tu script set_size.py
de la siguiente manera:
## Create a set of numbers
my_set = {1, 2, 3, 4, 5}
## Print the set
print(my_set)
## Remove elements from the set until it is empty
while len(my_set) > 0:
## Remove an arbitrary element from the set
element = my_set.pop()
print("Removed element:", element)
print("The set is now:", my_set)
print("The set is now empty.")
Guarda el archivo y ejecútalo:
python set_size.py
Deberías ver una salida similar a la siguiente (el orden de los elementos eliminados puede variar):
{1, 2, 3, 4, 5}
Removed element: 1
The set is now: {2, 3, 4, 5}
Removed element: 2
The set is now: {3, 4, 5}
Removed element: 3
The set is now: {4, 5}
Removed element: 4
The set is now: {5}
Removed element: 5
The set is now: set()
The set is now empty.
En este ejemplo, usamos la función len()
para verificar si el conjunto está vacío en cada iteración del bucle while
. El método pop()
elimina un elemento arbitrario del conjunto. El bucle continúa hasta que el conjunto está vacío.