Here are the four ways to create an empty list in Python.
- Using square brackets [ ]
- Using list constructor()
- Using list comprehension
- Using * Operator
Method 1: Using square brackets []
You can use the square brackets [ ] and assign them to a variable, which will become an empty list.
You can verify by printing type and length. If length returns 0, the list is empty; otherwise, it is not.
Visual Representation
Example
empty_list = []
# Print the empty list
print(empty_list)
# Print the type
print(type(empty_list))
# Print the length
print(len(empty_list))
Output
[]
<class 'list'>
0
An empty list evaluates to False in boolean context:
print(bool(empty_list))
Output
False
However, there is another way to check if the list is empty.
Method 2: Using list() constructor
The list() constructor creates a new list object. If no argument is given to the list constructor, it returns an empty list.
Visual Representation
Example
empty_list = list()
# Print the empty list
print(empty_list)
# Print the type
print(type(empty_list))
# Print the length
print(len(empty_list))
Output
[]
<class 'list'>
0
Method 3: Using list comprehension
This method is less common and inefficient but useful in specific scenarios.
Visual Representation
Example
empty_list = [x for x in range(0)]
# Print the empty list
print(empty_list)
# Print the type
print(type(empty_list))
# Print the length
print(len(empty_list))
Output
[]
<class 'list'>
0
Method 4: Using * Operator
This method is used for creating a list with repeated elements and it is not recommended for creating empty list.
Visual Representation
Example
empty_list = [*()]
# Print the empty list
print(empty_list)
# Print the type
print(type(empty_list))
# Print the length
print(len(empty_list))
Output
[]
<class 'list'>
0
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.