How do I remove 'None' items from the end of a list in Python
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]
If you don't want to modify the list, you can just find the first index from the right that isn't None and slice to it:
def shrink(l):
for i in range(len(l) - 1, -1, -1):
if l[i] is not None:
return l[:i + 1]
return l[:0]
If you do want to modify the list in-place, you can just delete the slice:
def shrink(l):
for i in range(len(l) - 1, -1, -1):
if l[i] is not None:
break
else:
i = -1
del l[i + 1:]