Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python remove null items from list

I created the following list in python for DynamoBIM:

a = [["f", "o", "c"], [null, "o", null], [null, "o", null]]

I want to remove the null items from this list to create this list:

a = [["f", "o", "c"], ["o"], ["o"]]

I've attempted list.remove(x), filters, for-loops, and a number of other methods but cannot seem to get rid of these buggers.

How can I do this?

like image 657
Blake Avatar asked Aug 29 '26 00:08

Blake


1 Answers

Assuming you mean None by null, you can use a list comprehension:

>>> null = None
>>> nested_list = [["f", "o", "c"], [null, "o", null], [null, "o", null]]
>>> [[x for x in y if x] for y in nested_list]
[['f', 'o', 'c'], ['o'], ['o']]

In case null is some other value, you can alter the above to set the value of null as that something else, and alter the comprehension to:

>>> null = None # Replace with your other value
>>> [[x for x in y if x != null] for y in nested_list]
[['f', 'o', 'c'], ['o'], ['o']]
like image 112
Anshul Goyal Avatar answered Aug 31 '26 13:08

Anshul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!