Search code examples
python-3.4

In Python how remove extra space elements from two dimensional array?


For eg.

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

and i want as

newlist = [['2','2'],['3','3'],['4','4']]

is there any list comprehensive compact way to achieve this like for 1D array we have [x for x in strings if x] is there any thing similar to this.


Solution

  • I think you mean you wish to remove empty elements fromm your 2darray. If that is the case then:

    old_list = [['2', '2', '', ''], ['3', '3', '', ''], ['4', '4', '', '']]
    new_list = [[instance for instance in sublist if len(instance)>0] for sublist in old_list]
    

    If you wish to remove elements containing only whitespace(spaces etc), then yoy may do something like:

    old_list = [['2', '2', '', ''], ['3', '3', '', ''], ['4', '4', '', '']]
    new_list = [[instance for instance in sublist if not instance.isspace()] for sublist in old_list]