gurkha_dawg gurkha_dawg - 3 months ago 10
Python Question

How can i print the square roots of odd numbers in a given list by using lis comprehension only?

The below gives only the odd numbers, but not the square roots.
How can I add additional features like writing the square roots for the odd numbers?

my_list=[x for x in range(1,10) if x%2!=0]

print my_list

Answer

Where you insert the value of x into the array, take the square root of it.

my_list=[x**.5 for x in range(1,10) if x%2!=0]

You can also use the math module, and specifically, the math.sqrt function.

import math
my_list = [math.sqrt(x) for x in range(1,10) if x%2!=0]