Try a list comprehension:
h_list = ['h1','h2','h3','h4','h5']
d_list = [
[1, None, 3, ' ', 5],
[1, ' ', 2, ' ', 9]
]
empty = [' ', None]
h_list = [' ' if any(b[i] in empty for b in d_list) else v for i, v in enumerate(h_list)]
print(h_list)
Output:
['h1', ' ', 'h3', ' ', 'h5']
Breaking down this part of the code:
h_list = [' ' if any(b[i] in empty for b in d_list) else v for i, v in enumerate(h_list)]
First, lets have only
[(i, v) for i, v in enumerate(h_list)]
The above will be a list of the indices and values of each element in h_list.
Now, we use an if statement to determine when to add the ' '. First, we need to recognize the any() function:
any(b[i] in empty for b in d_list)
returns True if any of the arrays inside d_list at index i is in the empty list. We want None and ' ' to be in place for all the strings in h_list that its index returns a ' ' or None for any of the lists in d_list, so:
[' ' for i, v in enumerate(h_list) if any(b[i] in empty for b in d_list)]
Finally, we want to use the original string if not any(b[i] in empty for b in d_list). For that, we use an else statement (note that with an else, the statements get shifted to the left side of the for loop.):
h_list = [' ' if any(b[i] in empty for b in d_list) else v for i, v in enumerate(h_list)]