Reputation: 4991
I have the following list:
a = [[['trial1', 'trial2'], 4], [[], 2]]
and I want to remove the list that have inside an empty list.So the following result:
c = [[['trial1', 'trial2'], 4]]
I am using the following code:
c = []
for b in a:
temp =[x for x in b if x]
if len(temp)>1:
c.append(temp)
It works ok, but it seems not to be a 'good way' of doing this task. Is there a more elegant way?
Upvotes: 3
Views: 67
Reputation: 31662
You could use list comprehension
and all
function to check whether everything in the list evaluted to the True
:
c = [i for i in a if all(i)]
print(c)
[[['trial1', 'trial2'], 4]]
Upvotes: 1
Reputation: 23203
You may use filter
built-in function.
a = [[['trial1', 'trial2'], 4], [[], 2]]
assert filter(lambda o: [] not in o, a) == [[['trial1', 'trial2'], 4]]
Since in Python 3 filter is lazy, you may need explicit conversion to list.
assert list(filter(lambda o: [] not in o, a)) == [[['trial1', 'trial2'], 4]]
Upvotes: 0