Open In App

Python – Remove empty List from List

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with python, we can have a problem in which we need to filter out certain empty data. These can be none, empty string, etc. This can have applications in many domains. Let us discuss certain ways in which the removal of empty lists can be performed. 

Method 1: Using list comprehension: This is one of the ways in which this problem can be solved. In this, we iterate through the list and don’t include the list which is empty. 

Example

Python3




# Python3 code to Demonstrate Remove empty List
# from List using list comprehension
 
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove empty List from List
# using list comprehension
res = [ele for ele in test_list if ele != []]
 
# printing result
print("List after empty list removal : " + str(res))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 2: Using filter() method

This is yet another way in which this task can be performed. In this, we filter None values. The none values include empty lists as well and hence these get removed.

Example

Python3




# Python3 Code to Demonstrate Remove empty List
# from List using filter() Method
 
# Initializing list by custom values
test_list = [5, 6, [], 3, [], [], 9]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Removing empty List from List
# using filter() method
res = list(filter(None, test_list))
 
# Printing the resultant list
print("List after empty list removal : " + str(res))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 3: Using function definition 

Python3




# Python Code to Remove empty List from List
 
def empty_list_remove(input_list):
    new_list = []
    for ele in input_list:
        if ele:
            new_list.append(ele)
    return new_list
 
 
# input list values
input_list = [5, 6, [], 3, [], [], 9]
 
# print initial list values
print(f"The original list is : {input_list}")
# function-call & print values
print(f"List after empty list removal : {empty_list_remove(input_list)}")


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Above defined method(Method 3) is best optimized method among all three.

Method 4: Using len() and type() methods.If the length is zero then the list is empty.

Python3




# Python3 code to Demonstrate Remove empty List
 
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
new_list=[]
# Remove empty List from List
for i in test_list:
    x=str(type(i))
    if(x.find('list')!=-1):
        if(len(i)!=0):
            new_list.append(i)
    else:
        new_list.append(i)
# printing result
print("List after empty list removal : " + str(new_list))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Method 5: Using remove() method

Python3




# Python3 code to Demonstrate Remove empty List
 
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove empty List from List
while [] in test_list :
    test_list.remove([])
 
# printing result
print("List after empty list removal : " + str(test_list))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(n), where n is length of list
Auxiliary Space: O(n)

Method 6 : Using list(),map(),join() and replace() methods

Python3




# Python3 code to Demonstrate Remove empty List
 
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
x=list(map(str,test_list))
y="".join(x)
y=y.replace("[]","")
y=list(map(int,y))
 
# printing result
print("List after empty list removal : " + str(y))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Method:  Using enumerate function

Python3




test_list = [5, 6, [], 3, [], [], 9]
res = [ele for i,ele in enumerate(test_list) if ele != []]
print(res)


Output

[5, 6, 3, 9]

Method: Using filter function

Python




# Python3 code to Demonstrate Remove empty List
 
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove empty List from List
res = filter(None, test_list)
 
# printing result
print("List after empty list removal : " ,res)


Output

The original list is : [5, 6, [], 3, [], [], 9]
('List after empty list removal : ', [5, 6, 3, 9])

Method: Using lambda function

Python3




# Python3 Code to Demonstrate Remove empty List
# from List using lambda function
 
# Initializing list by custom values
test_list = [5, 6, [], 3, [], [], 9]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Removing empty List from List
# using lambda function
res = list(filter(lambda x: x != [], test_list))
 
# Printing the resultant list
print("List after empty list removal : " + str(res))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Method: Using Recursion method 

Python3




# Python3 code to Demonstrate Remove empty List
#defining recursive function to remove empty list
def remove_empty(start,oldlist,newlist):
  if start==len(oldlist):  #base condition
    return newlist
  if oldlist[start]==[]:  #checking the element is empty list or not
    pass
  else:
    newlist.append(oldlist[start])   #appending non empty list element to newlist
  return remove_empty(start+1,oldlist,newlist)  #recursive function call
 
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
result=remove_empty(0,test_list,[])
# printing result
print("List after empty list removal : " ,result)


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal :  [5, 6, 3, 9]

Method: Using itertools.filterfalse()

Python3




# Python3 Code to Demonstrate Remove empty List
# from List
import itertools
 
# Initializing list by custom values
test_list = [5, 6, [], 3, [], [], 9]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Removing empty List from List
# using lambda function
res = list(itertools.filterfalse(lambda x: x == [], test_list))
 
# Printing the resultant list
print("List after empty list removal : " + str(res))


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method: Using the map() function

 Use the map function to iterate through the original list and remove empty lists.

Python3




# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove empty List from List
# using map() function
res = list(map(lambda x: x if x != [] else None, test_list))
res = [x for x in res if x != None]
 
# printing result
print("List after empty list removal : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(N)
Auxiliary Space: O(N)

Using re module

Python3




import re
  
# input list values
input_list = [5, 6, [], 3, [], [], 9]
  
# print initial list values
print(f"The original list is : {input_list}")
  
# removing empty list from list
res = list(filter(None, [x for x in input_list if not re.match('\[\]', str(x))]))
  
# print resultant list
print(f"List after empty list removal : {res}")


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method: Using the pop()

Python3




# Define the test list
test_list = [5, 6, [], 3, [], [], 9]
# Print the original list
print("The original list is : " + str(test_list))
# Counter variable 'i' to keep track of the current index
i = 0
# While loop to go through all elements of the list
while i < len(test_list):
    # If the current element is an empty list, remove it from the list
    if test_list[i] == []:
        test_list.pop(i)
    # Else, increment the counter variable
    else:
        i += 1
# Reassign the result to the original list after removing all empty lists
res = test_list
# Print the result
print("List after empty list removal : " + str(res))
 
 
#This code is contributed by Jyothi pinjala.


Output

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

Time Complexity: O(N)
Auxiliary Space: O(1)



Similar Reads

Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Remove trailing empty elements from given list
Given a list, the task is to remove trailing None values from last of the list. Let's discuss a few methods to solve the given task. Examples: Input: [1, 2, 3, 4, None, 76, None, None] Output: [1, 2, 3, 4, None, 76] Input: [1, 2, None, None, None, None, None, 5] Output: [1, 2, None, None, None, None, None, 5] Method #1: Using naive method C/C++ Cod
7 min read
Python - Ways to remove multiple empty spaces from string List
Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of the number of spaces. This has applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1
6 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preprocessing. Let us discuss certain ways in which this ta
7 min read
Python program to remove the nth index character from a non-empty string
Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approach uses a new string variable for storing the modi
4 min read
How to remove empty tags using BeautifulSoup in Python?
Prerequisite: Requests, BeautifulSoup, strip The task is to write a program that removes the empty tag from HTML code. In Beautiful Soup there is no in-built method to remove tags that has no content. Module Needed:bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python
2 min read
Remove all empty files within a folder and subfolders in Python
In this article, we will see how to remove all empty files within a folder and its subfolders in Python. We occasionally produce some empty files that are not needed. Here, we will use the below functions/methods to remove all empty files within a folder and its subfolder imported from the OS module and glob module. MethodDescriptionos.walk(path)Ge
4 min read
Python | First Non-Empty String in list
Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the 1st valid element. Let's discuss certain ways in which we can find the first Non-Empty String. Method #1 : Usi
5 min read
Practice Tags :
three90RightbarBannerImg