Reputation:
I am trying to remove blank elements/rows from a 2D list in python.
[['a', 'b', 'c', 'd'],
[], [], [], [], [], [],
['a', 'b', 'c', 'd'],
['a', 'b', 'c', 'd']]
sorry if this is simple but I have never had this problem in matlab and am stumped!
Upvotes: 1
Views: 769
Reputation: 1123590
filter()
with None
will remove empty values for you:
lst = filter(None, lst)
Alternatively you could use a list comprehension for the same result:
lst = [nested for nested in lst if nested]
Demo:
>>> lst = [['a', 'b', 'c', 'd'], [], [], [], [], [], [], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
>>> filter(None, lst)
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
>>> [nested for nested in lst if nested]
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
Upvotes: 5
Reputation: 354
Suppose the outer list is named list
, then you can remove inner empty list as follows:
list = [['61710480', '385950.51', '6526136.92', '59.369\n'],
[], [], [], [], [], [],
['61710487', '381808.8', '6519876.8', '53.292\n'],
['61710488', '381808.8', '6519876.8', '53.183\n']]
list = [l for l in list if len(l)>0]
Upvotes: -2