Skip to content
Advertisement

How do I remove ‘None’ items from the end of a list in Python

A have a list that might contain items that are None. I would like to remove these items, but only if they appear at the end of the list, so:

[None, "Hello", None, "World", None, None]
# Would become:
[None, "Hello", None, "World"]

I have written a function, but I’m not sure this is the right way to go about it in python?:

def shrink(lst):
    # Start from the end of the list.
    i = len(lst) -1
    while i >= 0:
        if lst[i] is None:
            # Remove the item if it is None.
            lst.pop(i)
        else:
            # We want to preserve 'None' items in the middle of the list, so stop as soon as we hit something not None.
            break
        # Move through the list backwards.
        i -= 1

Also a list comprehension as an alternative, but this seems inefficient and no more readable?:

myList = [x for index, x in enumerate(myList) if x is not None or myList[index +1:] != [None] * (len(myList[index +1:]))]

What it the pythonic way to remove items that are ‘None’ from the end of a list?

Advertisement

Answer

Discarding from the end of a list is efficient.

while lst[-1] is None:
    del lst[-1]

Add a safeguard for IndexError: pop from empty list if necessary. It depends on your specific application whether proceeding with an empty list should be considered normal or an error condition.

while lst and lst[-1] is None:
    del lst[-1]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement