how to remove negetive value in nested list

Viewed 80

I start python programming new and I have write this 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)

In this code I want to remove elements that have negative value, but when two negative value is together the code does not delete or remove the second value, what can I do? please help me.

2 Answers

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]
[[item for item in arr if item >= 0] for arr in y]
Related