14
votes

Is there an elegant pythonic way of removing trailing empty elements from a list? A sort of list.rstrip(None). So

[1, 2, 3, None, 4, None, None]

should result in

[1, 2, 3, None, 4]

I guess this could be generalized to removing trailing elements of any particular value.

If possible, I would like to have this done as a single line (readable) expression

12

12 Answers

21
votes

If you want to get rid of only None values and leave zeros or other falsy values, you could do:

while my_list and my_list[-1] is None:
    my_list.pop()

To remove all falsy values (zeros, empty strings, empty lists, etc.) you can do:

my_list = [1, 2, 3, None, 4, None, None]
while not my_list[-1]:
    my_list.pop()
print(my_list)
# [1, 2, 3, None, 4]
9
votes

The following explicitly checks for None elements:

while l and l[-1] is None:
    l.pop()

It can be generalized as follows:

f = lambda x: x is None
while l and f(l[-1]):
    l.pop()

You can now define different functions for f to check for other conditions.

4
votes

Try this

>>> x=[1, 2, 3, None, 4, None, None]
>>> while x[-1] is None:
    x.pop()
4
votes
def remove_trailing(l, remove_value=None):
    i = len(l)
    while i > 0 and l[i - 1] == remove_value:
        i -= 1
    return l[:i]
1
votes

For a one-line solution:

In [30]: from itertools import dropwhile

In [31]: list(reversed(tuple(dropwhile(lambda x: x is None, reversed([1, 2, 3, None, 4, None, None])))))
Out[31]: [1, 2, 3, None, 4]

If you want to reuse it, here's a definition in point-free style:

In [36]: from functional import compose, partial

In [37]: varargs = lambda *args: args

In [38]: compose_mult = compose(partial(reduce, compose),varargs) # compose which takes variable number of arguments. Innermost function to the right.

In [39]: compose_mult(list, reversed, tuple, partial(dropwhile, lambda x: x is None), reversed)([1, 2, 3, None, 4, None, None])
Out[39]: [1, 2, 3, None, 4]
1
votes

I never accepted an answer because I wasn't really happy with solutions offered. Here's another solution (1 line and no library dependencies) that I'm not entirely happy with either:

a = [1, 2, None, 3, None, None]
reduce(lambda l, e: [e]+l if l or e is not None else [], reversed(a), [])
0
votes

If you're looking for an one-liner, it could be like this:

a = [1, 2, 3, None, 4, None, None]
b = [x for n, x in enumerate(a) if any(y is not None for y in a[n:])]
print b

Note that it's quadratic (in the worst case).

For any falsy value, it's even simpler:

b = [x for n, x in enumerate(a) if any(a[n:])]
0
votes

If you really need to compromise readability here is what I'd do.

>>> from itertools import takewhile
>>> l=[1,2,3,None,4,5,None,None]
>>> l[:-len(list(takewhile(lambda x: x==None, reversed(l))))]
[1,2,3,None,4,5]
-1
votes

Here's yet another one-liner:

>>> l = [1, 2, 3, None, 4, None, None]
>>> [l[i] for i in range(len("".join(map(lambda x: {None: " "}.get(x, "_"), l)).rstrip()))]
[1, 2, 3, None, 4]

These things are fun!

EDIT

I just realized that the list comprehension is completely unnecessary. Slicing should work just fine:

>>> l[:len("".join(map(lambda x: {None: " "}.get(x, "_"), l)).rstrip())] 
-1
votes

What about recursion + slicing?

>>> rstrip = lambda x, elts=(None,): rstrip(x[:-1], elts) if x and x[-1] in elts else x
>>> rstrip([1, 2, 3, None])
[1, 2, 3]
>>> rstrip([1, 2, 3, None], (None, 3))
[1, 2]

Note: I'm assuming that you're not looking for the most computationally efficient solution here...

-1
votes

What about:

[a[i] for i in range(len(a)) if a[i:] != [None] * (len(a) - i) ]
-1
votes

The more_itertools project implements rstrip for any iterable:

iterable = [1, 2, 3, None, 4, None, None]
list(mit.rstrip(iterable, lambda x: x in {None}))
# [1, 2, 3, None, 4]

more_itertools.rstrip accepts an iterable and predicate. See the source code for details.