Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lstrip(), rstrip() for lists

Tags:

python

list

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.

like image 573
Andreas Jung Avatar asked Jan 09 '12 06:01

Andreas Jung


People also ask

Can you Rstrip a list in Python?

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.

Does strip work on lists?

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.

What does Lstrip and Rstrip do?

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.


2 Answers

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]
like image 156
Anders Waldenborg Avatar answered Oct 14 '22 12:10

Anders Waldenborg


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!
like image 38
FatihAkici Avatar answered Oct 14 '22 13:10

FatihAkici