Remove blank values from nested list using python

I have nested list in python which looks like

print(list)
#which gives output:
[['', 'A', '15 / 12 / 2020  -  00:10', '11.1'], ['','11.13', '10.95', '83.43'], 
['','83.98', '83.41','0'],['','1', '214', '0']]

I want to remove all blank values (' ') from nested list

Upvotes: 0

Views: 262

Answers (4)

Stan11
Stan11

Reputation: 284

We can also do this using the join() and split() function

my_list = [['', 'A', '15 / 12 / 2020  -  00:10', '11.1'], ['','11.13', '10.95', '83.43'], ['','83.98', '83.41',
 '0', ],['','1', '214', '0']]

new_list = []
for item in my_list:
    sub_list = ' '.join(item).split()
    new_list.append(sub_list)

print(new_list)

Output

[['A', '15', '/', '12', '/', '2020', '-', '00:10', '11.1'], ['11.13', '10.95', '83.43'], ['83.98', '83.41', '0'], ['1', '214', '0']]

Upvotes: 1

oezzi
oezzi

Reputation: 104

I would suggest you use a filter method which tests if the string length > 0

def isNotEmpty(entry):
    return len(entry) > 0

Have a look for filters https://www.programiz.com/python-programming/methods/built-in/filter

Upvotes: 1

JacksonPro
JacksonPro

Reputation: 3275

here is one way of doing it using list comprehension

lst = [[x for x in y if x != ''] for y in lst ]

since your first elements are empty string you may also use:

lst = [y[1:] for y in lst]

Upvotes: 2

Atif Rizwan
Atif Rizwan

Reputation: 685

You can use remove() method

final_list = []
for lst in aa:
    lst.remove('')
    final_list.append(lst)
print(final_list )

Upvotes: 1

Related Questions