How to Remove None (Null) Values from a List in Python

How to remove None (null) values from a Python list, with a list comprehension, filter(), in-place and nested-list versions, and the filter(None) mistake to avoid.

Mahzaib MirzaMahzaib MirzaFebruary 27, 20233 min read0 comments
How to Remove None (Null) Values from a List in Python

Python does not have a null value. The equivalent is None. The cleanest way to remove None values from a list is a list comprehension that keeps everything that is not None:

values = [1, None, 2, None, 3]

clean = [x for x in values if x is not None]

print(clean)  # [1, 2, 3]

This creates a new list and leaves the original unchanged. The rest of this page covers the other ways to do it, and one common shortcut that removes more than you intended.

Method 1: list comprehension

A list comprehension builds a new list from the items that pass a condition. Test with is not None, not != None. PEP 8, Python's style guide, says comparisons to singletons like None should be done with is or is not.

names = ['Ana', None, 'Ben', None, 'Cara']

names = [n for n in names if n is not None]

print(names)  # ['Ana', 'Ben', 'Cara']

Method 2: filter()

filter() keeps the items for which a function returns true. It returns an iterator, so wrap it in list():

values = [1, None, 2, None, 3]

clean = list(filter(lambda x: x is not None, values))

print(clean)  # [1, 2, 3]

The filter(None, ...) trap

You will often see filter(None, values) used as a shortcut. Passing None as the function keeps only the truthy items. That removes None, but also 0, '', False and empty containers:

values = [0, 1, None, '', 'a', False, [], 5]

print(list(filter(None, values)))
# [1, 'a', 5]  - 0, '', False and [] were removed too

print([x for x in values if x is not None])
# [0, 1, '', 'a', False, [], 5]  - only None was removed

If your list can contain zeros or empty strings that you want to keep, use is not None.

Method 3: remove them in place

A list comprehension creates a new list. If other variables refer to the same list and need to see the change, assign to a slice instead. That updates the existing list object:

values = [1, None, 2, None, 3]
alias = values

values[:] = [x for x in values if x is not None]

print(values)  # [1, 2, 3]
print(alias)   # [1, 2, 3]  - the same list, updated

Without the [:], values = [...] would point values at a new list and alias would keep the old one.

Method 4: a loop with remove()

list.remove(None) deletes only the first None it finds. To remove all of them, repeat until none are left:

values = [1, None, 2, None, 3]

while None in values:
    values.remove(None)

print(values)  # [1, 2, 3]

This works, but it scans the list again for every None and shifts items each time, so it gets slow on long lists. Prefer a list comprehension.

Remove None from a list of lists

Apply the same comprehension to each inner list:

rows = [[1, None, 2], [None, 3], [4, 5, None]]

clean = [[x for x in row if x is not None] for row in rows]

print(clean)  # [[1, 2], [3], [4, 5]]

Remove None values from a dictionary

A dictionary comprehension does the same for key and value pairs:

data = {'name': 'Ana', 'phone': None, 'city': 'Lisbon'}

clean = {k: v for k, v in data.items() if v is not None}

print(clean)  # {'name': 'Ana', 'city': 'Lisbon'}

What about NaN?

float('nan') is a number, not None, so is not None keeps it. NaN is also never equal to itself, so x != x is true only for NaN. Use math.isnan() to filter both:

import math

values = [1.5, None, float('nan'), 2.5]

def is_missing(x):
    return x is None or (isinstance(x, float) and math.isnan(x))

clean = [x for x in values if not is_missing(x)]

print(clean)  # [1.5, 2.5]

Which method should I use?

  • List comprehension: the default choice. Clear, fast and keeps zeros and empty strings.

  • filter() with a lambda: equivalent, if you prefer a functional style.

  • Slice assignment: when the same list object must be updated for everyone who holds a reference.

  • filter(None, ...): only when you really want to drop every falsy value.

Frequently asked questions

Is None the same as null in Python?

Yes, None is Python's way of representing "no value", like null in other languages. There is no null keyword in Python.

Does filter(None, my_list) remove zeros?

Yes. It removes every falsy item, including 0, '', False and empty lists, not just None.

How do I remove only the first None from a list?

Use my_list.remove(None). It removes the first match and raises a ValueError if there is none, so check None in my_list first if that is possible.

Share:
Mahzaib Mirza

Written by

Mahzaib Mirza

Software developer & Founder of Coders Vibe.

Related Posts

Liked this post?

Get the next one in your inbox the moment it's published. No spam, unsubscribe anytime.

0 Comments

Leave a comment