Reputation: 21
Working in Python, how would I write code to remove negatives from an unknown list of integers using for loops and if statements?
def mod_lis (list):
for i in range(len(list)):
if list[i] < 0:
del list[i]
return list
Upvotes: 2
Views: 416
Reputation: 4184
The problem with your code is that you modify your list during your for loop. The result is that you jump over elements this way and get an IndexError soon since your list has been shortened.
You can do this with this list comprehension:
mylist = [val for val in mylist if val>=0]
Upvotes: 3
Reputation: 5887
It's better to make a copy of the list without selected items, but if you have to modify in place, try this:
def remove_negatives(list):
pos = 0
for item in list:
if item >= 0:
list[pos] = item
pos += 1
del list[pos:]
Upvotes: 0
Reputation: 34146
You can use filter()
and a lambda
function:
my_list = filter(lambda x : x >= 0, mylist)
Upvotes: 0