how to remove negetive value in nested list

Question:

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?

Asked By: saraafr

||

Answers:

[[item for item in arr if item >= 0] for arr in y]
Answered By: ksha

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]
Answered By: azro

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)
Answered By: ariankazemi

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]]
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.