Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only positive numbers in list comprehension in python

Trying to create a list of positive numbers using single line but it's not working for me. Need help

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]

My code :

newlist = [n if n>0 else pass for n in numbers]

why else pass is not working?

like image 785
SQA_LEARN Avatar asked Dec 18 '25 20:12

SQA_LEARN


1 Answers

You nearly had it:

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]

newlist = [n for n in numbers if n > 0]

output:

[34.6, 44.9, 68.3, 44.6, 12.7]

In case you needed an else, to replace negative numbers with None, for instance: (this is not what you asked for, but I include it here for completeness)

newlist = [n if n > 0 else None for n in numbers]

output:

[34.6, None, 44.9, 68.3, None, 44.6, 12.7]

Lastly, if you wanted to convert all numbers to positive, using abs:

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]

newlist = [abs(n) for n in numbers]

output:

[34.6, 203.4, 44.9, 68.3, 12.2, 44.6, 12.7]
like image 93
Reblochon Masque Avatar answered Dec 21 '25 12:12

Reblochon Masque