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
Use the str. rstrip() method to remove the trailing zeros. The result won't contain trailing zeros.
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.
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]
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.
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