user3699095
user3699095

Reputation:

How to remove blank 2D list rows?

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

Answers (2)

Martijn Pieters
Martijn Pieters

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

Emisilve86
Emisilve86

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

Related Questions