Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing trailing empty elements in a list

Tags:

python

list

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

like image 814
Dmitry B. Avatar asked Apr 05 '12 19:04

Dmitry B.


People also ask

How do I remove trailing zeros from a list in Python?

Use the str. rstrip() method to remove the trailing zeros. The result won't contain trailing zeros.

How do you remove null elements from a list in Python?

There are a several ways to remove null value from list in python. we will use filter(), join() and remove() functions to delete empty string from list.


2 Answers

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]
like image 158
alan Avatar answered Sep 18 '22 21:09

alan


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.

like image 36
Simeon Visser Avatar answered Sep 20 '22 21:09

Simeon Visser