mashedpotatoes
mashedpotatoes

Reputation: 435

How to truncate a list based on an arbitrary value?

I want to trim a list of all trailing a values, where a is some arbitrary value.

Example:

Another example. Say a = None:

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

Answers (2)

Hardik Tewari
Hardik Tewari

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

kaya3
kaya3

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

Related Questions