I want to remove 0
only from my list:
>>> mylist = [0, 1, None, 2, False, 1, 0]
<
The x is not 0
approach works, but is probably not optimal. There speed enhancements by using a list comprehension
instead of using calls to list()
and to filter()
.
Running this in a Jupyter notebook and taking advantage of the builtin %timeit
magic to see how quickly each of these can return the result.
mylist = [0, 1, None, 2, False, 1, 0]
Using list() and filter()
%timeit list(filter(lambda x: x is not 0, mylist))
**1.12 µs** ± 17.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Using a list comprehsion
%timeit [i for i in mylist if i is not 0]
**411 ns** ± 8.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
We see that the list comprehension technique is significantly faster.