How to Filter None Values from a Mixed List in Python
Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.
Python code
7 linesmixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]
filtered_list = [item for item in mixed_list if item is not None]
print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
Output
Original list: [1, None, 'hello', None, 3.14, None, [1, 2], None]
Filtered list: [1, 'hello', 3.14, [1, 2]]
Original length: 8, Filtered length: 4
How it works
The list comprehension [item for item in mixed_list if item is not None] iterates over each element and keeps only those that are not None. The is not None check is preferred over != None because it checks identity rather than equality, which is faster and more explicit. This approach preserves the original list and creates a new filtered list, leaving the original untouched. It works for any type of elements—integers, strings, floats, lists, and more—because it only filters out None itself.
Common mistakes
- Using `if item` instead of `if item is not None` — this filters out falsy values like 0, '', and [] as well.
- Forgetting that `None` is a singleton — using `== None` works but is less idiomatic.
- Modifying the list while iterating over it, which can lead to skipped items or unexpected behavior.
Variations
- Use `filter(lambda x: x is not None, mixed_list)` to get a filter object, then convert to a list with `list()`.
- Use a `for` loop with `append` to build the filtered list for extra clarity in teaching contexts.
Real-world use cases
- Cleaning API responses that may contain null fields before processing the data further.
- Removing missing values from database query results before aggregating statistics.
- Filtering out placeholder entries in configuration lists loaded from JSON files.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.