Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading