I am trying to achieve something very simple here which should be possible in a elegant one-liner but I can't figure out how:
Let's say I have a list my_list = [1, None, 3, 4]
and want to add a constant val = 3
to each of the numeric elements to obtain my_list + val = [4, None, 6, 7]
:
This operation can be done using a somewhat bulky loop with a condition for None
values:
my_list = [1, None, 3, 4]
val = 3
for idx, el in enumerate(my_list):
if el is not None:
my_list[idx] += val
print(my_list)
>>> [4, None, 6, 7]
However, I have the strong feeling that there must be a more elegant way of doing that. I attempted something along these lines:
my_list = list(map(lambda x: x+val, filter(None, my_list)))
print(my_list)
>>> [4, 6, 7]
But then the None
elements are gone and I need to preserve them.
Any thoughts appreciated!