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.
In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive.
Explanation: To pick out only the negative numbers from a given list 'l', the correct list comprehension statement would be: [x for x in l if x<0].
If we want to reverse the elements ( sub_list ) in the nested list, we can use the indexing method. my_list[::-1] — It will reverse the elements in the nested list. It will create a copy of the nested list. It won't modify the original list.
The task of removal of element generally doesn’t pose any challenge, but sometimes, we may have a more complex problem than just removing a single element or performing removal in just a normal list. Problem can be removing all occurrences of nested list. Let’s discuss certain ways in which this problem can be solved.
So first we use the MAX formula to remove negative values. As you can see the formula returns 0 wherever negative values are expected. But what if the data already has 0 value and now you need to differentiate between actual 0 value and this formula returned 0 value.
Given an array arr [] of size N, the task is to remove all negative elements from this array. Explanation: The only negative element of the array is -4. Approach 1: The given problem can be solved using the following steps : Create a vector newArr to store only positive elements. Now traverse the array arr, and push positive element in newArr.
Method #1 : Using list comprehension. The combination of above functions can be used to solve this problem. In this, we perform the task of removing negative elements by iteration in one liner using list comprehension. test_list = [5, 6, -3, -8, 9, 11, -12, 2]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With