Reputation: 143
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
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
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
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