nodel
nodel

Reputation: 561

Replace all negative values in a list

I'm trying to solve this problem on codewars and I'm completely stumped:

y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]

How would I do this?

I tried to do:

for e in range(len(y)):
    try:
        if y[e] < 0:
            y[e] = z[e]
    except:
        pass

But this would only work if the negatives correspond to what is in z.

Upvotes: 3

Views: 2715

Answers (4)

ospahiu
ospahiu

Reputation: 3525

One-liner. Emulate queue behavior using pop(). (Note this consumes z)

>>> print([num if num > 0 else z.pop(0) for num in y])
[1, 3, 2, 8, 5, 4]

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107287

If you are sure that number of negative numbers is always equal with z you can convert z to an iterable and use a list comprehension for creating your new list:

In [9]: z = iter(z)

In [10]: [next(z) if i < 0 else i for i in y]
Out[10]: [1, 3, 2, 8, 5, 4]

Note that if the length of z is shorter than number of negative numbers it will raise an StopIteration error.

Upvotes: 10

Neil A.
Neil A.

Reputation: 841

Your code:

for e in range(len(y)):
    if y[e] < 0: y[e] = z[e]

The problem with your code is let's say the 5th element is negative. You are attempting to set the 5th element of y to the 5th element of z. Instead, you should use a counter variable to track which element to substitute.

element_z_index = 0
for e in range(len(y)):
    if y[e] < 0:
        y[e] = z[element_z_index]
        element_z_index += 1

Upvotes: 0

Curtis Lusmore
Curtis Lusmore

Reputation: 1872

You're trying to use the same index for both lists, which doesn't appear to be the correct behaviour from your example. For example, the -1 in y is at index 4, but is replaced by the 5 in z at index 2.

zindex = 0
for yindex in range(len(y)):
    if y[yindex] < 0:
        y[yindex] = z[zindex]
        zindex += 1

Upvotes: 0

Related Questions