Home »
Python »
Python programs
Python program to remove empty list from a list of lists
Here, we are going to learn how to remove empty list from a list of lists in Python?
Submitted by Shivang Yadav, on March 26, 2021
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered sets of values enclosed in square brackets [].
List of lists is a list that contains lists as its elements.
We have a list that contains other lists (empty and non-empty). And we need to return a list that does not contain any empty string.
To perform this task, we need to iterate the list and then in the resultant list exclude all the empty elements.
Program to remove the empty list from a list of lists
# Python program to remove empty list
# from a list of lists
# Initializing list of lists
listofList = [[5], [54, 545,9], [], [1, 4, 7], [], [8, 2, 5] ]
# Printing original list
print("List of List = ", end = " ")
print(listofList)
nonEmptyList = []
# Iterating using loop and eliminating empty list
nonEmptyList = [listEle for listEle in listofList if listEle != []]
# Printing list without empty list
print("List without empty list: ", end = " " )
print(nonEmptyList)
Output:
List of List = [[5], [54, 545, 9], [], [1, 4, 7], [], [8, 2, 5]]
List without empty list: [[5], [54, 545, 9], [1, 4, 7], [8, 2, 5]]
Another method
Python provides its users with in-built functions on data structures to perform the task easily.
On such method is filter() method
Syntax:
filter(function, iterable)
Program to remove the empty list from a list of lists using filter() method
# Python Program to remove empty list from a list of lists
# Initializing list of lists
listofList = [[5], [54, 545,9], [], [1, 4, 7], [], [8, 2, 5] ]
# Printing original list
print("List of List = ", end = " ")
print(listofList)
nonEmptyList = []
# eliminating empty lists using the filter method...
nonEmptyList = list(filter(None, listofList))
# Printing list without empty list
print("List without empty list: ", end = " " )
print(nonEmptyList)
Output:
List of List = [[5], [54, 545, 9], [], [1, 4, 7], [], [8, 2, 5]]
List without empty list: [[5], [54, 545, 9], [1, 4, 7], [8, 2, 5]]
Python List Programs »