Python equivalent to replace() in R

Viewed 38

Is there a powerful replace function in Python, something equivalent to replace(x, l, y) in R? e.g.

x = [0,0,0,0,0,0,0,0,0, 0]
l = [True,False,True,True,False,False,False,False,True, False]
y = [5, 6, 7, 8]

The number of values in y matches the number of True in l. In R, replace(x, l, y) will have x replaced by y corresponding to the True positions in l.

Is there a similar function in Python I can call? If not, any suggestions how to make it working?

Thanks much in advance!

1 Answers

Since the number of Trues and the number of elements in y are the same, we can a generator over y, and then use a list comprehension to build the result. We extract from y if the corresponding element in l is True, else we extract from x:

iter_y = iter(y)

[next(iter_y) if l_item else x_item for l_item, x_item in zip(l, x)]

This outputs:

[5, 0, 6, 7, 0, 0, 0, 0, 8, 0]
Related