Search code examples
pythonstrip

How to remove all instances of None from the end of a list?


Python has a string method called rstrip():

>>> s = "hello world!!!"
>>> s.rstrip("!")
'hello world'

I want to implement similar functionality for a Python list. That is, I want to remove all instances of a given value from the end of a list. In this case, the value is None.

Here's some starting examples:

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

I want the end results to be:

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

Here's my solution so far:

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

Solution

  • If you want to modify the list in-place, then your solution is good, just make sure you handle the case when the list is empty:

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

    If you want to compute a new list, you can adapt your solution into:

    def stripNone(l):
        if not l:
            return []
        
        rlim = 0
        for x in reversed(l):
            if x is None:
                rlim += 1
            else:
                break
        
        return l[: len(l) - rlim]
    

    There is also itertools.dropwhile, but you have to perform two reversals:

    def stripNone(l):
        return list(dropwhile(lambda x: x is None, l[::-1]))[::-1]