Python

How to remove empty lists from a Python List

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment