Mpizos Dimitris
Mpizos Dimitris

Reputation: 4991

Removing list having empty list

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

Answers (4)

Anton Protopopov
Anton Protopopov

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

javad
javad

Reputation: 528

c = [l for l in a if [] not in l]

Upvotes: 4

khelwood
khelwood

Reputation: 59096

Use a list comprehension:

c = [x for x in a if [] not in x]

Upvotes: 4

Łukasz Rogalski
Łukasz Rogalski

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

Related Questions