Use len() Function
In the previous step, you learned how to get the size of a set using the len()
function. In this step, we will explore more advanced ways to use the len()
function with sets, including using it within conditional statements and loops.
Let's start by modifying our set_size.py
script to include a conditional statement that checks if the set is empty. Open your set_size.py
file in the VS Code editor and modify it as follows:
## 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.")
Save the file and run it:
python set_size.py
You should see the following output:
{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.
Now, let's modify the script to create an empty set and check its size. Change the first line of your set_size.py
script to create an empty set:
## 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.")
Save the file and run it again:
python set_size.py
This time, you should see the following output:
set()
The size of the set is: 0
The set is empty.
As you can see, the len()
function returns 0 for an empty set, and our conditional statement correctly identifies that the set is empty.
Now, let's use the len()
function in a loop. Suppose we want to remove elements from a set until it is empty. Modify your set_size.py
script as follows:
## 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.")
Save the file and run it:
python set_size.py
You should see output similar to the following (the order of removed elements may vary):
{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.
In this example, we use the len()
function to check if the set is empty in each iteration of the while
loop. The pop()
method removes an arbitrary element from the set. The loop continues until the set is empty.