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
x
4
1
[None, "Hello", None, "World", None, None]
2
# Would become:
3
[None, "Hello", None, "World"]
4
I have written a function, but I’m not sure this is the right way to go about it in python?:
JavaScript
1
13
13
1
def shrink(lst):
2
# Start from the end of the list.
3
i = len(lst) -1
4
while i >= 0:
5
if lst[i] is None:
6
# Remove the item if it is None.
7
lst.pop(i)
8
else:
9
# We want to preserve 'None' items in the middle of the list, so stop as soon as we hit something not None.
10
break
11
# Move through the list backwards.
12
i -= 1
13
Also a list comprehension as an alternative, but this seems inefficient and no more readable?:
JavaScript
1
2
1
myList = [x for index, x in enumerate(myList) if x is not None or myList[index +1:] != [None] * (len(myList[index +1:]))]
2
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
1
3
1
while lst[-1] is None:
2
del lst[-1]
3
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
1
3
1
while lst and lst[-1] is None:
2
del lst[-1]
3