Explore Non-Empty Lists
In this step, you will learn about non-empty lists in Python and how to identify them. A list is a fundamental data structure in Python that can hold an ordered collection of items. An empty list is a list that contains no items, while a non-empty list contains at least one item. Understanding how to work with lists is crucial for many programming tasks.
First, let's create a Python script to explore non-empty lists. Open the VS Code editor in the LabEx environment and create a new file named list_check.py
in the ~/project
directory.
## ~/project/list_check.py
my_list = [1, 2, 3]
if my_list:
print("The list is not empty.")
else:
print("The list is empty.")
In this script, we create a list called my_list
containing the numbers 1, 2, and 3. The if my_list:
statement checks if the list is non-empty. In Python, an empty list evaluates to False
in a boolean context, while a non-empty list evaluates to True
.
Now, let's run the script to see the output. Open the terminal in VS Code and navigate to the ~/project
directory (you should already be in this directory by default). Then, execute the script using the python
command:
python list_check.py
You should see the following output:
The list is not empty.
This confirms that our script correctly identifies a non-empty list.
Now, let's modify the script to use an empty list and see what happens. Change the my_list
variable to an empty list:
## ~/project/list_check.py
my_list = []
if my_list:
print("The list is not empty.")
else:
print("The list is empty.")
Run the script again:
python list_check.py
This time, you should see the following output:
The list is empty.
This demonstrates that an empty list is correctly identified as empty.
This simple example shows how you can use the boolean evaluation of lists to determine whether they are empty or non-empty. This is a common technique in Python programming.