Last modified: Apr 06, 2023 By Alexander Williams
Remove Empty String From List and Array in Python
Methods to Remove Empty String From List
Using a list comprehension
# List
my_list = ["hello", "", "world", "", ""]
# Create a new list using a list comprehension that includes only non-empty strings
my_list = [x for x in my_list if x != ""]
print(my_list)
Output:
['hello', 'world']
Using the filter() function with a lambda function
# List
my_list = ["hello", "", "world", "", ""]
# Create a new list using the filter() function with a lambda function
my_list = list(filter(lambda x: x != "", my_list))
print(my_list)
Output:
['hello', 'world']
Using a for loop
# List
my_list = ["hello", "", "world", "", ""]
# Create a new list using a for loop that includes only non-empty strings
new_list = []
for x in my_list:
if x != "":
new_list.append(x)
print(new_list)
Output:
['hello', 'world']
Methods to Remove Empty String From Array
Using a list comprehension
import numpy as np
my_array = np.array(["hello", "", "world", "", ""]) # List
# Create a new numpy array using a list comprehension that includes only non-empty strings
my_array = np.array([x for x in my_array if x != ""])
print(my_array)
Output:
['hello' 'world']
Using the numpy delete() function
import numpy as np # pip install numpy
my_array = np.array(["hello", "", "world", "", ""]) # List
# Find the indices of the empty strings
indices = np.where(my_array == "")[0]
# Delete the elements with these indices using the numpy delete() function
my_array = np.delete(my_array, indices)
print(my_array)
Output:
['hello' 'world']
Using a for loop
import numpy as np
my_array = np.array(["hello", "", "world", "", ""])
# Create a new list using a for loop that includes only non-empty strings
new_array = np.array([])
for x in my_array:
if x != "":
new_array = np.append(new_array, x)
print(new_array)
Output:
['hello' 'world']