There may be a chances of having a python list containing empty lists, if you would like to remove all of them this guide helps you.
Remove empty lists from a Python List:
There are two different ways to do it, lets see both of them.
1. Python filter()
Python built-in filter()
function is used to filer the elements in a list, we can use this function to filter the empty lists.
if __name__ == '__main__':
fruits_list = [[], 'apple',[], [], [], [], 'grapes', [], 'banana']
print("Before filtering")
print(fruits_list)
print("After filtering")
fruits_list = list(filter(None,fruits_list))
print(fruits_list)
Output:
Before filtering
[[], 'apple', [], [], [], [], 'grapes', [], 'banana']
After filtering
['apple', 'grapes', 'banana']
2. List Comprehension:
The same thing we can do with python’s list comprehension like below.
if __name__ == '__main__':
fruits_list = [[], 'apple',[], [], [], [], 'grapes', [], 'banana']
print("Before filtering")
print(fruits_list)
print("After filtering with list comprehension")
fruits_list = [fruit for fruit in fruits_list if fruit != []]
print(fruits_list)
Output:
Before filtering
[[], 'apple', [], [], [], [], 'grapes', [], 'banana']
After filtering with list comprehension
['apple', 'grapes', 'banana']
References:
Happy Learning 🙂