Q:

Python program to remove empty list from a list of lists

belongs to collection: Python List Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to multiply all numbers of a list... >>
<< Python program to extract keywords from the list...