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 = [
Solution 1:
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 > 0elseNonefornin 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]
Post a Comment for "Only Positive Numbers In List Comprehension In Python"