Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Negative Elements in a List - Python

So, I`m trying to write a function that removes the negative elements of a list without using .remove or .del. Just straight up for loops and while loops. I don`t understand why my code doesn`t work. Any assistance would be much appreciated.

def rmNegatives(L):
    subscript = 0
    for num in L:
        if num < 0:
            L = L[:subscript] + L[subscript:]
        subscript += 1
    return L
like image 883
Tahmoor Cyan Avatar asked Apr 30 '26 03:04

Tahmoor Cyan


2 Answers

Why not use list comprehension:

new_list = [i for i in old_list if i>=0]

Examples

>>> old_list = [1,4,-2,94,-12,-1,234]
>>> new_list = [i for i in old_list if i>=0]
>>> print new_list
[1,4,94,234]

As for your version, you are changing the elements of the list while iterating through it. You should absolutely avoid it until you are absolutely sure what you are doing.

As you state that this is some sort of exercise with a while loop, the following will also work:

def rmNegatives(L):
    i = 0
    while i < len(L):
        if L[i]<0:
            del L[i]
        else:
            i+=1
    return L
like image 66
sshashank124 Avatar answered May 01 '26 20:05

sshashank124


You could also use filter, if you so please.

L = filter(lambda x: x > 0, L)
like image 41
Aesthete Avatar answered May 01 '26 21:05

Aesthete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!