I want to Extract only nonzero numbers from python list . This is what I am doing . but it isnt working it seems .
d=[num if num for num in d]
where d is my original list and again I want output in same list
In [5]: d =[1,2,3,0,0,9]
In [6]: d = filter(None,d)
In [7]: d
Out[7]: [1, 2, 3, 9]
Some timings:
In [30]: %timeit filter(None,d)
1000000 loops, best of 3: 727 ns per loop
In [31]: %timeit filter(lambda x: x != 0, d)
100000 loops, best of 3: 3.89 µs per loop
In [32]: %timeit [x for x in d if x != 0]
100000 loops, best of 3: 2.33 µs per loop
In [33]: %timeit [num for num in d if num]
100000 loops, best of 3: 2.04 µs per loop
As you only have numbers in your list filter(None,d) will work fine. If you had any other falsey values like empty lists [] etc.. it would also remove them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With