-2

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
  • 107,498
  • 14
  • 145
  • 201

3 Answers3

3
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
  • 3,863
  • 2
  • 14
  • 39
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
  • 3,938
  • 1
  • 13
  • 29
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
  • 1,965
  • 1
  • 12
  • 24