Reputation: 435
I want to trim a list of all trailing a
values, where a
is some arbitrary value.
Example:
[1, 2, 3, a, 5, a, a, a, a]
→ [1, 2, 3, a, 5]
Another example. Say a = None
:
[1, None, 2, None, 3, None, None, None, 7, None, None, None, None, None, None]
→[1, None, 2, None, 3, None, None, None, 7]
filter
removes them but also removes the ones in between. I'd like a way to maintain the order, preserve the elements in between, and only remove the trailing ones.
Upvotes: 0
Views: 52
Reputation: 113
Suppose your list is [1, 2, 3, -1, 5, -1, -1, -1, -1]
where -1
is the arbitrary value.
list = [1, 2, 3, -1, 5, -1, -1, -1, -1]
i = len(list) - 1
while i >= 0 and list[i] == -1:
i = i-1
print(list[:i+1])
The code above will remove all the arbitrary values that occur continuously at the end. Hope it helps!
Upvotes: 1
Reputation: 51162
Simplest solution is to use pop
, which removes the element at the end of the list. This solution is in-place, meaning it changes the contents of the input list.
def remove_trailing(lst, val=None):
while lst and lst[-1] == val:
lst.pop()
Usage:
>>> lst = [1, 2, 3, None, 5, None, None, None, None]
>>> remove_trailing(lst)
>>> lst
[1, 2, 3, None, 5]
Upvotes: 3