Python lists are a very useful data structure. Remember that Python lists are an iterable, ordered, mutable, data structure. You can create a list of your toys like so:
Recall that lists need not contain elements of the same type. Furthermore, you an add to lists, delete elements from lists since they are mutable.
Creating an empty Python List using square brackets
To create an empty list, all you need to do is to set it equal to “[]”, like so:
This produces:
As shown above, the mytoys variable is initialized to an empty list containing zero elements. You can verify that it contains no elements by doing:
This will output:
Creating an empty Python List using the list() constructor
A second way to create an empty list is to do:
This produces the expected output:
Evaluating an empty list
An empty list when used in a boolean context evaluates to False. A non-empty list evaluates to True.
If you try:
You will get:
If on the other hand, you tried:
You will get:
Which is more efficient? Square brackets or list constructor?
The square brackets approach is the more efficient way to create an empty list because the list constructor is more general purpose and uses more checks and logic before the list is created.
You need not take our word for it. Let us use the timeit() module to time two pieces of code. Below is a program that declares both pieces of code and times them:
The result is:
(Try running this program a few times to convince yourself that this is a consistent pattern. In fact the speed difference is at least 1-2 orders of magnitude.)
Checking if a list is empty
Another useful function is to be able to check if a list is empty. We can use the len() function for it:
This produces:
as expected.
A second way to do it is to simply evaluate the list in the conditional context as we suggested earlier:
This gives:
Emptying a List
If your list is not empty and you desire to empty it, we can use the clear() method:
This yields:
Of course since lists are mutable, you could also have done:
with the same results:
In this blog post you have learnt all about empty lists: how to create them, how to test for emptiness, and how to empty a non-empty list.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.