How can I add zero's in empty slots in a list in python?

Viewed 68

How can I add zero's in empty slots in a list in python?

for example

list_1 = ['2','4',' ','3',' ','1',' ']

output I want:

 ['2','4','0','3','0','1','0']
2 Answers

Here is a list comprehension that will do it:

list_1 = ['0' if i.strip() == '' else i for i in list_1]

You can also do it like this

list_1 = ['2','4','','3','','1','']
for i in list_1:
    if i =="":
        list_1[list_1.index(i)] = 0
print(list_1)
Related