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?
The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
There are a several ways to remove null value from list in python. we will use filter(), join() and remove() functions to delete empty string from list.
It can be fixed by adding a return statement on each conditional statement and removing the print.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With