I have a bunch of huge lists with integers. These lists may start or end with a couple of zeroes.
Is there an easy way for strip either the zeroes on the left or right side from the list?
Something analogous to lstrip()
or rstrip()
for strings?
The data looks like
[0,0,0,1,2,3,4]
or
[1,2,3,4,0,0,0]
I must be able to individually lstrip()
or rstrip()
. I do not need a strip from both sides of the list.
How do you strip every item in a list Python? Using list. clear() is the recommended solution in Python 3 to remove all items from the list.
The Python String strip() function works only on strings and will return an error if used on any other data type like list, tuple, etc.
rstrip(): returns a new string with trailing whitespace removed. It's easier to remember as removing white spaces from “right” side of the string. lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.
You could use itertools.dropwhile()
:
>>> L = [0, 0, 1, 1, 2, 2, 0]
>>> list(itertools.dropwhile(lambda x: x == 0, L))
[1, 1, 2, 2, 0]
There is a more efficient solution than the built-in itertools.dropwhile()
. You can use the almighty collections.deque
, which would be the ideal data structure for this task, because its left or right pop
is O(1)
. Here is the left-strip case, and the right-strip is going to be just the mirror image of it:
from collections import deque
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)
l = [0, 0, 1, 1, 2, 2, 0]
print(noLeadingZero(l))
# Result:
# [1, 1, 2, 2, 0]
Let's test its performance against the following code that utilizes the built-in itertools.dropwhile()
:
from itertools import dropwhile
print(list(dropwhile(lambda x: x == 0, l)))
Here is the performance test:
import timeit
print timeit.timeit(
setup= """from itertools import dropwhile
l = [0, 0, 1, 1, 2, 2, 0]""",
stmt="""list(dropwhile(lambda x: x == 0, l))""") #2.308
print timeit.timeit(
setup= """from collections import deque
l = [0, 0, 1, 1, 2, 2, 0]
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)""",
stmt="""noLeadingZero(l)""") #1.684 -> Win!
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