Jailbone
Jailbone

Reputation: 93

Removing empty sublists from nested list

How do I get from this:

a = [[[1, 1], [], [2,2]], [[2,2], [], [1, 1]]]

to this:

a = [[[1,1], [2,2]], [[2,2], [1,1]]]

quickly? I am trying to use a list comprehension but can't figure it out.

Upvotes: 1

Views: 75

Answers (3)

Neeraj Kumar
Neeraj Kumar

Reputation: 404

this solution is working for me.

a = [[[1, 1], [], [2,2]], [[2,2], [], [1, 1]]]
list_new = []
for i in a :
    list_new.append([x for x in i if x != []])

Upvotes: 1

Alireza75
Alireza75

Reputation: 501

use this

a=[[i for i in lst if i] for lst in a]

Upvotes: 2

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

You can use a list comprehension:

a = [[sublst for sublst in lst if sublst] for lst in a]

Otherwise you can use the filter function:

[list(filter(None, lst)) for lst in a]

Upvotes: 2

Related Questions