Python: How to remove empty lists from a list?
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]
How to remove empty lists in python
Since empty lists evaluate to False
with bool
, you can use filter
with None
. Note L
may be any iterable of lists, you need not begin with a list of lists.
L = [['JOB', 'APPLIED', 'FOR'], [], [], [], ['TEST'], ['SOMETHING ELSE']]
res = list(filter(None, L))
print(res)
[['JOB', 'APPLIED', 'FOR'], ['TEST'], ['SOMETHING ELSE']]
Remove empty strings from a list of strings
I would use filter
:
str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)
Python 3 returns an iterator from filter
, so should be wrapped in a call to list()
str_list = list(filter(None, str_list))
Remove empty nested lists - Python
I think what you want to do is
tscores = [x for x in tscores if x != []]
which make a list of only the none empty lists in tscores
How can I remove empty lists from within another list?
According to the docs for any(iterable)
:
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.
Hence when a list of Strings is passed to Any
and if all of the elements in list are empty strings then it will return False
as Empty String is equivalent to False
.
So in your code replacing the second last line with:
fixed_paras = [x for x in paras if any(x)]
will eliminate the lists with empty strings too.
Note: This answer is based on juanpa.arrivillaga's comment
Removing empty sublists from a nested list
You have a mix of lists and strings, both of which are iterables. You need to explicitly test for lists here, and either recurse or use a stack:
def clean_nested(l):
cleaned = []
for v in l:
if isinstance(v, list):
v = clean_nested(v)
if not v:
continue
cleaned.append(v)
return cleaned
Demo:
>>> mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
>>> clean_nested(mynestedlist)
[[['Foo']], [['Bar']], ['FOO'], 'BAR']
Note that this solution removes all but the outermost list if there are empty lists inside empty lists:
>>> nested_empty = [[[],[],[],[],[],[]],[[],['Bar'],[], []], ['FOO'], 'BAR']
>>> clean_nested(nested_empty)
[[['Bar']], ['FOO'], 'BAR']
>>> all_nested_empty = [[[],[],[],[],[],[]],[[],[],[], []], []]
>>> clean_nested(all_nested_empty)
[]
Python - delete empty lists from a list
You can use any(a_list)
, which is True
if any element of a_list
evaluates to True
, as non-empty strings do.
data = [['#0721', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['GBE COD', '746', '$2.00', '', '$1,492.00'], ['GBW COD', '13,894', '$0.50', '', '$6,947.00'], ['GOM COD', '60', '$2.00', '', '$120.00'], ['GB WINTER FLOUNDER', '94,158', '$0.25', '', '$23,539.50'], ['GOM WINTER FLOUNDER', '3,030', '$0.50', '', '$1,515.00'], ['GBE HADDOCK', '18,479', '$0.02', '', '$369.58'], ['GOM HADDOCK', '0', '$0.02', '', '$0.00'], ['GBW HADDOCK', '110,470', '$0.02', '', '$2,209.40'], ['HAKE', '259', '$1.30', '', '$336.70'], ['PLAICE', '3,738', '$0.40', '', '$1,495.20'], ['POLLOCK', '3,265', '$0.02', '', '$65.30'], ['WITCH FLOUNDER', '1,134', '$1.30', '', '$1,474.20'], ['SNE YT', '1,458', '$0.65', '', '$947.70'], ['GB YT', '4,499', '$0.70', '', '$3,149.30'], ['REDFISH', '841', '$0.02', '', '$16.82'], ['', '', '', '', ''], ['', '', '', '', ''], ['54 DAS @ $8.00/DAY = 432.00', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', '']]
non_empty = [sublist for sublist in data if any(sublist)]
print(non_empty)
[['#0721', '', '', '', ''],
['GBE COD', '746', '$2.00', '', '$1,492.00'],
['GBW COD', '13,894', '$0.50', '', '$6,947.00'],
['GOM COD', '60', '$2.00', '', '$120.00'],
['GB WINTER FLOUNDER', '94,158', '$0.25', '', '$23,539.50'],
['GOM WINTER FLOUNDER', '3,030', '$0.50', '', '$1,515.00'],
['GBE HADDOCK', '18,479', '$0.02', '', '$369.58'],
['GOM HADDOCK', '0', '$0.02', '', '$0.00'],
['GBW HADDOCK', '110,470', '$0.02', '', '$2,209.40'],
['HAKE', '259', '$1.30', '', '$336.70'],
['PLAICE', '3,738', '$0.40', '', '$1,495.20'],
['POLLOCK', '3,265', '$0.02', '', '$65.30'],
['WITCH FLOUNDER', '1,134', '$1.30', '', '$1,474.20'],
['SNE YT', '1,458', '$0.65', '', '$947.70'],
['GB YT', '4,499', '$0.70', '', '$3,149.30'],
['REDFISH', '841', '$0.02', '', '$16.82'],
['54 DAS @ $8.00/DAY = 432.00', '', '']]

Delete keys of a dictionary whose values are empty lists
What about:
new_d = dict((k,v) for k,v in d.items() if v)
And if you wish to overwrite d
just change new_d
to d
.
There is some risk that might gives the wrong results:
if v
when v = []
will evaluate to Falsly, same as 0
so it might remove wrong key. In my answer I didn't address that. One can refer to the following link to understand better: What is Truthy and Falsy? How is it different from True and False?
Related Topics
List All Base Classes in a Hierarchy of Given Class
How to Read One Single Line of CSV Data in Python
How to Install Xgboost Package in Python (Windows Platform)
Mixing Cdef and Regular Python Attributes in Cdef Class
Convert Pandas Datetimeindex to Unix Time
Add Zeros to a Float After the Decimal Point in Python
Django Rest Framework Post Nested Objects
Putting Many Python Pandas Dataframes to One Excel Worksheet
Keep Same Dummy Variable in Training and Testing Data
Python Read File as Stream from Hdfs
Passing Numpy Arrays to a C Function for Input and Output
Multithreaded Web Server in Python
About the Pil Error -- Ioerror: Decoder Zip Not Available
Getting Standard Errors on Fitted Parameters Using the Optimize.Leastsq Method in Python