0

I have this 2d list right here :

list = [ [1,2,3], [1,'',''], ['','','']] 

I want to delete every instance of '' in the list, so that the output should look like this:

>> [ [1,2,3],[1]] 

I think that deleting all the ''-s is gonna left me out with this list, so could you please also explain how to get rid of empty lists in 2d lists?

>> [ [1,2,3],[1],[]]

Thank you!

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218

3 Answers3

4
a = [[1,2,3], [1,'',''], ['','','']] 
b = [[i for i in item if i != ''] for item in a]
c = [item for item in b if item != []]
print(b)
print(c)

Output

[[1, 2, 3], [1], []]
[[1, 2, 3], [1]]
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
1

could also use filter:

lst = [ [1,2,3], [1,'',''], ['','','']] #don't use list to define a list
list(filter(None,[list(filter(None,l)) for l in lst]))

output:

[[1, 2, 3], [1]]
Derek Eden
  • 4,403
  • 3
  • 18
  • 31
0

A one liner with nested list comprehensions (not very dry though):

[[y for y in x if y != ''] for x in list if [y for y in x if y != ''] != []]
# [[1, 2, 3], [1]]
AidanGawronski
  • 2,055
  • 1
  • 14
  • 24