Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to remove empty lists from a list? [duplicate]

Tags:

python

list

I have a list with empty lists in it:

list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText'] 

How can I remove the empty lists so that I get:

list2 = ['text', 'text2', 'moreText'] 

I tried list.remove('') but that doesn't work.

like image 288
SandyBr Avatar asked Jan 30 '11 12:01

SandyBr


People also ask

How do I remove all empty lists from a list in Python?

Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x] to filter the list.

How do I remove a list from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do you remove two lists from a list in Python?

Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.


1 Answers

Try

list2 = [x for x in list1 if x != []] 

If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use

list2 = [x for x in list1 if x] 
like image 72
Sven Marnach Avatar answered Sep 25 '22 13:09

Sven Marnach