Reputation: 41
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!
Upvotes: 0
Views: 1033
Reputation: 4638
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]]
Upvotes: 1
Reputation: 2085
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]]
Upvotes: 0
Reputation: 4199
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]]
Upvotes: 4