Python: How to remove empty lists from a list?

PythonList

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

You can use filter() instead of a list comprehension:

list2 = filter(None, list1)

If None is used as first argument to filter(), it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

It might be slightly faster than the list comprehension, because it only executes a single function in Python, the rest is done in C.

Solution 3 - Python

Calling filter with None will filter out all falsey values from the list (which an empty list is)

list2 = filter(None, list1)

Solution 4 - Python

>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> list2 = [e for e in list1 if e]
>>> list2
['text', 'text2', 'moreText']

Solution 5 - Python

A few options:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

Solution 6 - Python

I found this question because I wanted to do the same as the OP. I would like to add the following observation:

The iterative way (user225312, Sven Marnach):

list2 = [x for x in list1 if x]

Will return a list object in python3 and python2 . Instead the filter way (lunaryorn, Imran) will differently behave over versions:

list2 = filter(None, list1)

It will return a filter object in python3 and a list in python2 (see this question found at the same time). This is a slight difference but it must be take in account when developing compatible scripts.

This does not make any assumption about performances of those solutions. Anyway the filter object can be reverted to a list using:

list3 = list(list2)

Solution 7 - Python

a = [[1,'aa',3,12,'a','b','c','s'],[],[],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]

b=[]
for lng in range(len(a)):
       if(len(a[lng])>=1):b.append(a[lng])
a=b
print(a)

Output:

[[1,'aa',3,12,'a','b','c','s'],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]

Solution 8 - Python

list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
list2 = []
for item in list1:
	if item!=[]:
		list2.append(item)
print(list2)

output:

['text', 'text2', 'moreText']

Solution 9 - Python

Adding to the answers above, Say you have a list of lists of the form:

theList = [['a','b',' '],[''],[''],['d','e','f','g'],['']]

and you want to take out the empty entries from each list as well as the empty lists you can do:

theList = [x for x in theList if x != ['']] #remove empty lists
for i in range(len(theList)):
    theList[i] = list(filter(None, theList[i])) #remove empty entries from the lists
    

Your new list will look like

theList = [['a','b'],['d','e','f','g']]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSandyBrView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonlunaryornView Answer on Stackoverflow
Solution 3 - PythonImranView Answer on Stackoverflow
Solution 4 - Pythonuser225312View Answer on Stackoverflow
Solution 5 - Pythonuser180100View Answer on Stackoverflow
Solution 6 - PythonjlandercyView Answer on Stackoverflow
Solution 7 - PythonArash.HView Answer on Stackoverflow
Solution 8 - PythonSUNITHA KView Answer on Stackoverflow
Solution 9 - PythonChidiView Answer on Stackoverflow