saraafr
saraafr

Reputation: 143

how to remove negetive value in nested list

I'm new to Python programming and I've written the following code:

y = [[-1, -2, 4, -3, 5], [2, 1, -6], [-7, -8, 0], [-5, 0, -1]]
for row in y:
    for col in row:
        if col < 0:
            row.remove(col)
print(y)

I want to remove elements with negative values from the nested list. However, when two negative values are adjacent, the code doesn't remove the second value. What modifications can I make to ensure the removal of all negative values?

Upvotes: 1

Views: 239

Answers (4)

XMehdi01
XMehdi01

Reputation: 1

You can use a combination of map and list comprehensions.

Here's an example:

y = [[-1, -2, 4, -3, 5], [2, 1, -6], [-7, -8, 0], [-5, 0, -1]]
y = list(map(lambda row: [col for col in row if col >= 0], y))
print(y)

Output:

[[4, 5], [2, 1], [0], [0]]

Upvotes: 0

ariankazemi
ariankazemi

Reputation: 191

You can use filter and lambda function:


    y = [[-1, -2, 4, -3, 5], [2, 1, -6], [-7, -8, 0], [-5, 0, -1]]

    y = [list(filter(lambda col: col >= 0, row)) for row in y]

    print(y)

Upvotes: 2

azro
azro

Reputation: 54148

You may never remove items form a list while iterating it, you'd keep the ones you need, the positive ones

y = [[col for col in row if col>=0] for row in y]

Upvotes: 5

ksha
ksha

Reputation: 2087

[[item for item in arr if item >= 0] for arr in y]

Upvotes: 3

Related Questions