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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With