In this tutorial, we will learn how to return an empty list in Python. An empty list is a list that contains no elements. We will cover different methods to return an empty list, and you can choose which approach best suits your needs.
Method 1: Creating an empty list using brackets []
The most straightforward method to create an empty list in Python is to use empty square brackets []. This approach is easy to read and understand. Here is an example:
1 2 3 4 5 |
def empty_list(): return [] my_list = empty_list() print(my_list) |
Output:
[]
Method 2: Creating an empty list using the list() constructor
Another way to create an empty list is by using the built-in list() function without any arguments.
1 2 3 4 5 |
def empty_list(): return list() my_list = empty_list() print(my_list) |
Output:
[]
Method 3: Returning an empty list in a function with a conditional statement
In some cases, you may want to return an empty list depending on the condition. You can use a conditional statement followed by the return
keyword to achieve this.
1 2 3 4 5 6 7 8 9 10 11 |
def maybe_empty_list(condition): if condition: return [] else: return [1, 2, 3] empty = maybe_empty_list(True) non_empty = maybe_empty_list(False) print(empty) print(non_empty) |
Output:
[] [1, 2, 3]
You can use a similar approach with the list() function if you prefer:
1 2 3 4 5 6 7 8 9 10 11 |
def maybe_empty_list(condition): if condition: return list() else: return [1, 2, 3] empty = maybe_empty_list(True) non_empty = maybe_empty_list(False) print(empty) print(non_empty) |
Output:
[] [1, 2, 3]
Conclusion
You have now learned multiple ways to return an empty list in Python. You can create an empty list using square brackets [], the list() function, or using conditional statements depending on your needs. Now you can choose the method that best fits your specific use case and integrate it into your code.