user3354021
user3354021

Reputation: 21

Removing negatives from an unknown list in Python

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

Answers (3)

SZIEBERTH &#193;d&#225;m
SZIEBERTH &#193;d&#225;m

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

Arpegius
Arpegius

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

Christian Tapia
Christian Tapia

Reputation: 34146

You can use filter() and a lambda function:

my_list = filter(lambda x : x >= 0, mylist)

Upvotes: 0

Related Questions