Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove 'None' items from the end of a list in Python [duplicate]

Tags:

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?

like image 767
leeman Avatar asked Oct 09 '19 17:10

leeman


People also ask

How do I remove something from the end of a list in Python?

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.

How do I remove None values from a 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.

How do you remove null elements from a list in Python?

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.

How do I remove print None in Python?

It can be fixed by adding a return statement on each conditional statement and removing the print.


1 Answers

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] 
like image 160
wim Avatar answered Sep 30 '22 06:09

wim