Home > Software engineering >  Python: function that exclude negative values from list and give back new list
Python: function that exclude negative values from list and give back new list

Time:02-10

I have list of numbers. I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me. Could you please suggest something.

This is the code which is working but it's loop:

new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

This function does not work. It gives me None.


data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]


def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)

CodePudding user response:

Use a simple comprehension:

data3 = [i for i in data2 if i > 0]
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]

For your function, data.append return nothing so you return None:

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            new_list.append(i)
    return new_list  # <- HERE

Usage:

data3 = preprocessing(data2)
print(data3)

# Output
[10, 32, 454, 31, 53, 31314, 53, 10]

CodePudding user response:

Your function prepocessing returns None because you call the return too early.

append() is a method of the list object that modifies the object and returns nothing. So when you return the result of this method, it returns None.

You could simply do this:

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            new_list.append(i)
    return new_list

CodePudding user response:

Corralien already gave good answers but I feel one is missing. To create an iterable which contains only >0 from data2:

new_iter = filter(lambda x: x > 0, data2)

Using an iterable may be advantageous in circumstances where you are later looping through the list but maybe not all of it. This way the list is only evaluated as far as you need it.

To turn it into a list, just do new_list = list(new_iter).

  • Related