How to Remove Falsy Values from List in Python Easily
To remove falsy values from a list in Python, use a list comprehension with
if item to keep only truthy values. For example, [item for item in my_list if item] creates a new list without falsy values like None, 0, '', or False.Syntax
The common syntax to remove falsy values from a list uses a list comprehension:
[item for item in original_list if item]
Here, original_list is your starting list.
The if item part filters out all values that Python treats as false, such as None, 0, empty strings '', empty lists [], and False.
python
[item for item in original_list if item]
Example
This example shows how to remove all falsy values from a list containing different types of falsy elements.
python
my_list = [0, 1, False, 2, '', 3, None, 4, [], 5] filtered_list = [item for item in my_list if item] print(filtered_list)
Output
[1, 2, 3, 4, 5]
Common Pitfalls
One common mistake is trying to remove falsy values by checking for None only, which misses other falsy values like 0 or empty strings.
Another pitfall is modifying the list while iterating over it, which can cause unexpected behavior.
python
# Wrong: only removes None, not other falsy values my_list = [0, None, '', False] filtered = [item for item in my_list if item is not None] print(filtered) # Output: [0, '', False] # Right: removes all falsy values filtered = [item for item in my_list if item] print(filtered) # Output: []
Output
[0, '', False]
[]
Quick Reference
- Falsy values in Python include:
None,False,0, empty strings'', empty lists[], empty tuples(), and empty dictionaries{}. - Use list comprehension with
if itemto filter out all falsy values. - This method creates a new list and does not modify the original list.
Key Takeaways
Use list comprehension with 'if item' to remove all falsy values from a list.
Falsy values include None, 0, False, empty strings, and empty collections.
Avoid checking only for None if you want to remove all falsy values.
Do not modify a list while iterating over it; create a new filtered list instead.
This method keeps only truthy values, making your list clean and useful.