user02
user02

Reputation: 293

Python- list comprehension. Removing NoneType or emty list from list of list

I would like to remove empty list and NoneType list in my list of lists. This is an example.

new_pop=[[[0,1,2,3],[4,5,6]],[[],[8,9]],[[1,2,3],None]]


value = None
empty =[]
for i in range(len(new_pop)):
    if value in new_pop[i] and [] in new_pop[i]:
        new_pop.remove(new_pop[i])

print(new_pop)

my desire result is

new_pop=[[[0,1,2,3],[4,5,6]]]

Upvotes: 0

Views: 567

Answers (2)

AChampion
AChampion

Reputation: 30258

If all you are trying to do is remove any sublist that includes None or [] then assuming that all items in your sublists are lists with contents then you can use a guard of all():

>>> [x for x in new_pop if all(x)]
[[[0, 1, 2, 3], [4, 5, 6]]]

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36023

new_pop = [sub for sub in new_pop if not (None in sub or [] in sub)]

Your code has two errors:

  1. You use and. sub = [[],[8,9]] satisfies None in sub but not None in sub and [] in sub, because it doesn't satisfy [] in sub. You need or.

  2. You're removing items from a list as you iterate over it. Never do that. Always create a new list, like I've done here.

Upvotes: 1

Related Questions