You can remove all None
values in a Python list in the following ways:
Using filter()
You can simply use the filter()
method to filter out all None
values from a list, for example, like so:
lst = [1, 2, None, 3, None, 4, 5, None] filtered_items = filter(lambda item: item is not None, lst) new_lst = list(filtered_items) print(new_lst) # [1, 2, 3, 4, 5] print(filtered_items) # <generator object <genexpr> at ...>
filter(function, iterable)
is actually equivalent to the generator expression (item for item in iterable if function(item))
.
Using Generator Expression
You can use a generator expression to filter out all None
values from a list in the following way:
lst = [1, 2, None, 3, None, 4, 5, None] filtered_items = (item for item in lst if item is not None) new_lst = list(filtered_items) print(new_lst) # [1, 2, 3, 4, 5] print(filtered_items) # <filter object at ...>
Using generator expression is similar to using list comprehension, however, it is more memory efficient comparatively. This is because list comprehension loads the entire list in memory, whereas a generator expression only loads the current value in memory.
Using List Comprehension
Using list comprehension, you can iterate over a list and return a new list with only items that are not None
, for example, like so:
lst = [1, 2, None, 3, None, 4, 5, None] new_lst = [item for item in lst if item is not None] print(new_lst) # [1, 2, 3, 4, 5]
Using a Loop
You may iterate over a list using a loop, and selectively add only non-none values, for example, like so:
lst = [1, 2, None, 3, None, 4, 5, None] new_lst = [] for item in lst: if item != None: new_lst.append(item) print(new_lst) #=> [1, 2, 3, 4, 5]
However, it might not be the best choice as it would create/overwrite a variable named "item
", which would persist even after the loop completes. Consider, for example, the following where the item
variable holds the last value from the original list after the loop completes:
lst = [1, 2, None, 3, None, 4, 5, None] new_lst = [] for item in lst: if item != None: new_lst.append(item) print(item) # None
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.