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:

JavaScript

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

JavaScript

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

JavaScript

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.

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement