Reputation: 2986
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.
Upvotes: 1
Views: 1323
Reputation: 1000
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]
Upvotes: 3
Reputation: 444
use this list comprehension:
list = [[x for x in a if x] for a in list]
Upvotes: 0
Reputation: 1769
You can achieve this using filter. Also unrelated but since list
is a reserved word it's best not to use it and try to come up with a more meaningful name, I've simply renamed it to original_list since the list()
method won't work otherwise.
original_list = [['2', '2', '', ''], ['3', '3', '', ''], ['4', '4', '', '']]
new_list = []
for sub_list in original_list:
new_sub_list = list(filter(None, sub_list))
new_list.append(new_sub_list)
print(new_list)
Or in short
new_list2 = [ list(filter(None, sub_list)) for sub_list in original_list ]
print(new_list2)
Upvotes: 1