[SOLVED] Python: function that exclude negative values from list and give back new list

Issue

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)

Solution

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]

Answered By – Corralien

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *