Python

[Python] Remove None from list object

[Python] Remove None from list object

We want to remove None from list object.
When we process data, sometimes it contains None value.
None is not integer nor string.
So it is not easy to use.
Today I introduce how to remove None from list object.


How to remove None from list object

Remove None from list object.
It means keeping values except None.

To say abstractly, it keeps values which meets particular condition.

There are 4 methods.

  • filter
  • filter + lambda
  • function in the list
  • function in the list with "is not None" condition

So I will introduce each methods with following list.

list_a = [0, 1, 2, 3, None, 5, 6, 7]
print(list_a)
# [0, 1, 2, 3, None, 5, 6, 7]


filter

In order to use filter, we should set None and list object in filter function.

Then it returns filter ofject.
Once you convert it to list ofject, you can see its content.

list_a_filtered = filter(None, list_a)
print(list_a_filtered)
print(list(list_a_filtered))
# <filter object at 0x0000025F40A48358>
# [1, 2, 3, 5, 6, 7]



It filters 0 and None.
In the function, 0 and None are evaluated as False.
So they are filtered.


filter + lambda

If you want to use lambda in filter function, its code will be like below.

list_a_filtered = filter(lambda a:a is not None, list_a)
print(list(list_a_filtered))
# [0, 1, 2, 3, 5, 6, 7]



In this case, only None is filtered.

Lambda condition is applied to each value in the list.
Then it returns a list whose values meet the is not None condition.


Function in the list

If we use function in the list, code will be like following.

list_a_filtered = [x for x in list_a if x]
print(list_a_filtered)
# [1, 2, 3, 5, 6, 7]



This solution also returns list that does not contains 0.
0 is evaluated as False.


Function in the list with "is not None" condition

If you want to keep 0, you can use the condition is not None.

list_a_filtered = [x for x in list_a if x is not None]
print(list_a_filtered)
# [0, 1, 2, 3, 5, 6, 7]



Then it keeps 0 and filters None.


Finally

When you want to remove None from list ofject, you can use filter or function in list.
With using is not None condition, you can filter None only.


If you felt this article is useful, please share.

にほんブログ村 IT技術ブログへ

-Python

© 2024 ITips