Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Remove empty strings from list of strings

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 task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list. 

Python3




# Python3 code to demonstrate
# removing empty strings
# using remove()
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using remove() to
# perform removal
while("" in test_list):
    test_list.remove("")
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method #2: Using List Comprehension More concise and better approach to remove all the empty strings, it just checks if the string is not empty and re-makes the list with all strings that are not empty. 

Python3




# Python 3 code to demonstrate
# removing empty strings
# using list comprehension
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using list comprehension to
# perform removal
test_list = [i for i in test_list if i]
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Time complexity: O(n)

Auxiliary space: O(n), where n is length of list

  Method #3 : Using join() + split() Combining both the join() and split() operations, this task can also be achieved. We first join all the strings so that empty space is removed, and then split it back to list so that the new list made now has no empty string. 

Python3




# Python3 code to demonstrate
# removing empty strings
# using join() + split()
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using join() + split() to
# perform removal
test_list = ' '.join(test_list).split()
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method #4: Using filter() Using filter() is the most elegant and fastest way to perform this task. This method is highly recommended because speed matters when we deal with large machine learning data set that may potentially contain empty string. 

Python3




# Python 3 code to demonstrate
# removing empty strings
# using filter()
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using filter() to
# perform removal
test_list = list(filter(None, test_list))
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method #5 : Using len() method.

Python3




# Python3 code to demonstrate
# removing empty strings
 
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print ("Original list is : " + str(test_list))
 
for i in test_list:
    if(len(i)==0):
        test_list.remove(i)
     
# Printing modified list
print ("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method: Using enumerate function

Python3




test_list = [' ', 'Lazyroar', ' ', 'is', 'best', ' ']
 
test_list = [i for a,i in enumerate(test_list) if i!=' ']
     
print (test_list)


Output

['Lazyroar', 'is', 'best']

Method #6: Using lambda function

Python3




# Python 3 code to demonstrate
# removing empty strings
# using lambda function
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using lambda function
test_list = list(filter(lambda x: len(x) > 0, test_list))
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method #7: Using filter with custom function

One approach to remove empty strings from a list of strings that is not mentioned in the article is using the filter() function with a custom function as the first argument. The custom function can check if the string is not empty, and filter() will return a filtered list with only the non-empty strings.

Here is an example of this approach:

Python3




def remove_empty_strings(string):
    return string != ""
 
test_list = ["", "Lazyroar", "", "is", "best", ""]
filtered_list = filter(remove_empty_strings, test_list)
print(list(filtered_list))  # Output: ['Lazyroar', 'is', 'best']


Output

['Lazyroar', 'is', 'best']

The time complexity of the filter() method is O(n), where n is the length of the list. This means that the time taken to execute this method increases linearly with the size of the list. In terms of auxiliary space, the filter() method requires O(n) auxiliary space. 

Method #8: Using recursion Function. 

Python3




# Python 3 code to demonstrate
# removing empty strings
# using recursive  function
 
def remove_empty(start,oldlist,newlist):
  if start==len(oldlist):return newlist  #base condition
  if oldlist[start]!="":  #checking if string is empty or not
    newlist.append(oldlist[start])
  return remove_empty(start+1,oldlist,newlist)
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using recursive function
test_list = remove_empty(0,test_list,[])
 
# Printing modified list
print("Modified list is : " + str(test_list))
 
#this code contributed by tvsk


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Method #9: Using itertools.filterfalse()

Python3




# Python 3 code to demonstrate
# removing empty strings
import itertools
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using lambda function
test_list = list(itertools.filterfalse(lambda x: x == '', test_list))
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Time Complexity: O(N)

Auxiliary Space: O(N)

Method #10: Using functools.reduce()

In this approach, we will use reduce method of Python which will help us iterate over the list and follow the following steps: 

  • Initialize the list with an empty string. 
  • Printing the string with an empty string. 
  • Using reduce method on the list with an empty string. 
  • reduce method takes the condition, original list, and initial result. 
  • On the basis of the condition reduce accumulate final result from the original list and assign it to a variable. 
  • Print the final list. 

Python




# Python3 code to demonstrate
# removing empty strings
# using reduce()
import functools
 
# initializing list
test_list = ["", "Lazyroar", "", "is", "best", ""]
 
# Printing original list
print("Original list is : " + str(test_list))
 
# using reduce() method
# perform removal
result = functools.reduce(lambda a, b: a+[b] if b else a, test_list, [])
 
# Printing modified list
print("Modified list is : " + str(result))


Output

Original list is : ['', 'Lazyroar', '', 'is', 'best', '']
Modified list is : ['Lazyroar', 'is', 'best']

Time Complexity: O(N)

Auxiliary Space: O(N)

RELATED ARTICLES

Most Popular

Recent Comments