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
Why not use list comprehension:
new_list = [i for i in old_list if i>=0]
>>> 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
You could also use filter, if you so please.
L = filter(lambda x: x > 0, L)
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