Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

You could also use filter, if you so please.

L = filter(lambda x: x > 0, L)

Solution 3:

A note to your code:

L = L[:subscript] + L[subscript:]

does not change your list. For example

>>> l = [1,2,3,4]
>>> l[:2] + l[2:]
[1, 2, 3, 4]

Other mistakes:

def rmNegatives(L):
    subscript = 0
    for num in L: # here you run over a list which you mutate
        if num < 0:
            L = L[:subscript] + L[subscript:] # here you do not change the list (see comment above)
        subscript += 1 # you have to do this only in the case, when you did not remove an element from the list
    return L

A running code would be:

def rmNegatives(L):
    subscript = 0
    for num in list(L):
        if num < 0:
            L = L[:subscript] + L[subscript+1:]
        else:
            subscript += 1
    return L

See the solutions of @Aesthete and @sshashank124 for better implementations of your problem...


Post a Comment for "Removing Negative Elements In A List - Python"