Learn About Empty Lists
In this step, you'll learn about empty lists in Python. An empty list is a list that contains no elements. It's like an empty container, ready to be filled with data. Understanding empty lists is crucial because they are often used as starting points for building more complex data structures or as default values in functions.
Let's start by creating an empty list in Python. You can do this using square brackets []
without any elements inside.
-
Open your VS Code editor in the LabEx environment.
-
Create a new file named empty_list.py
in the ~/project
directory.
~/project/empty_list.py
-
Add the following code to the empty_list.py
file:
## Creating an empty list
my_list = []
## Printing the list to see its content
print(my_list)
-
Save the file.
-
Now, run the script using the python
command in the terminal:
python ~/project/empty_list.py
You should see the following output:
[]
This confirms that you have successfully created an empty list.
Empty lists are useful for initializing variables or as a starting point for loops and conditional statements. For example, you might want to create an empty list to store the results of a calculation or to hold items that meet a certain condition.
Here's another example to illustrate the use of an empty list:
## Initialize an empty list
results = []
## Simulate some data
data = [1, 2, 3, 4, 5]
## Iterate through the data and add even numbers to the results list
for number in data:
if number % 2 == 0:
results.append(number)
## Print the results
print(results)
Save this code to even_numbers.py
in your ~/project
directory and run it:
python ~/project/even_numbers.py
The output will be:
[2, 4]
In this example, we started with an empty list called results
and then populated it with even numbers from the data
list. This demonstrates how empty lists can be dynamically filled with data based on certain conditions.