Compare with Desired Length
In this step, you will learn how to compare the length of a list with a desired length using conditional statements. This is a common task in programming when you need to validate data or perform different actions based on the size of a list.
We'll use the len()
function in conjunction with if
statements to check if a list's length matches a specific value.
Continue using the list_length.py
file you've been working on in the ~/project
directory.
Let's create a list and then check if its length is equal to a desired value:
## Create a list of names
names = ["Alice", "Bob", "Charlie"]
## Desired length
desired_length = 3
## Check if the length of the list is equal to the desired length
if len(names) == desired_length:
print("The list has the desired length.")
else:
print("The list does not have the desired length.")
Save the changes to list_length.py
and run the script:
python ~/project/list_length.py
The output should be:
The list has the desired length.
Now, let's modify the list and see what happens:
## Create a list of names
names = ["Alice", "Bob"]
## Desired length
desired_length = 3
## Check if the length of the list is equal to the desired length
if len(names) == desired_length:
print("The list has the desired length.")
else:
print("The list does not have the desired length.")
Save the changes to list_length.py
and run the script again:
python ~/project/list_length.py
The output should now be:
The list does not have the desired length.
You can also use other comparison operators, such as >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to), to compare the length of the list with the desired length.
For example:
## Create a list of numbers
numbers = [1, 2, 3, 4]
## Minimum length required
min_length = 3
## Check if the length of the list is greater than or equal to the minimum length
if len(numbers) >= min_length:
print("The list meets the minimum length requirement.")
else:
print("The list does not meet the minimum length requirement.")
Save the changes to list_length.py
and run the script:
python ~/project/list_length.py
The output should be:
The list meets the minimum length requirement.
This step demonstrates how to use the len()
function in conjunction with conditional statements to compare the length of a list with a desired length, allowing you to perform different actions based on the size of the list.