How to remove null values from list in Python

In Python programming, we may face a problem like we are having a list of strings. But the list of strings contains empty strings or null values in it. Even some values only containing white spaces. But we have to remove those empty strings or null values from the list. What would be the most efficient way to remove null values from the list? Today in this Python tutorial we will learn How to remove null values from list in Python with some easy examples.

Remove null values from a list in Python

Here is a list having some null values in it. Or you can say having some empty strings in it.

codespeedy_list = ['hey','there','','whats','','up']
print(codespeedy_list)

Output:

['hey', 'there', '', 'whats', '', 'up']

Now you can see here we got two null values in this list of strings.

The fastest way to remove the empty strings from the list in Python is to use filter(None,List)

Let’s see how to use that

codespeedy_list = ['hey','there','','whats','','up']
print(codespeedy_list)
codespeedy_list = list(filter(None,codespeedy_list))
print(codespeedy_list)

Output:



['hey', 'there', '', 'whats', '', 'up']
['hey', 'there', 'whats', 'up']

The above technique I have shown you is the most efficient way to remove null values from a list of strings in Python. But there are other ways too to do the same.

You may also like to learn,

codespeedy_list = ['hey','there','','whats','','up']
print(codespeedy_list)
codespeedy_list = list(filter(bool, codespeedy_list))
print(codespeedy_list)

This one will give you the same output.

codespeedy_list = ['hey','there','','whats','','up']
print(codespeedy_list)
codespeedy_list = list(filter(len, codespeedy_list))
print(codespeedy_list)

Same output again.

 

Remove strings containing only whitespaces from a list in Python

Suppose you have a list where you got some strings that are not exactly null or empty but contain only white spaces. Then how to remove those strings?

Here is a solution to remove strings consist of only whitespaces in Python

codespeedy_list = ['hey','there','','  ','whats','','up']
print(codespeedy_list)
codespeedy_list = list(filter(str.strip, codespeedy_list))
print(codespeedy_list)

Output:

['hey', 'there', '', '  ', 'whats', '', 'up']
['hey', 'there', 'whats', 'up']

It will remove both null strings and whitespaces string from a list in Python

 

Leave a Reply

Your email address will not be published. Required fields are marked *