1

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!

2 Answers2

6

You're looking for the following

[i + val if i is not None else i for i in my_list]

It simply adds the val to each element if it isn't none, otherwise it preserves the value

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 1
    Ah, whenever I think I finally got the full potential of list comprehensions I learn something new. Perfect, thanks :) – Florian Drawitsch Oct 23 '19 at 09:56
  • @FlorianDrawitsch - Really it isn't anything to do with list comprehensions its just using a [ternary operator](https://stackoverflow.com/q/394809/1324033) :) – Sayse Oct 23 '19 at 09:58
  • Well, but if such ternary operators couldn't be used within list comprehensions, the solution would still require writing a loop or no? – Florian Drawitsch Oct 23 '19 at 10:12
  • @FlorianDrawitsch - A list comprehension is of the form `[ for in ]` so all I'm doing here is setting the return value to the result of the ternary operator, you could've used the `map` function you were writing in a similar way to the other answer – Sayse Oct 23 '19 at 10:17
-1

you can do this way with lambda function

val = 3
solution = list(map(lambda x: x if x is None else x+val, my_list))
sahasrara62
  • 10,069
  • 3
  • 29
  • 44