Create a list of numbers with their square roots


This Python code calculates the square root of each number in a list using the math.sqrt() function and stores the results in a new list. Here's how the code works:

  • import math: This line imports the math module, which contains various mathematical functions and constants, including the sqrt() function for calculating square roots.
  • numbers = [1, 4, 9, 16, 25]: This line initializes a variable named numbers and assigns it a list containing five numbers.
  • square_roots = [math.sqrt(x) for x in numbers]: This line of code initializes a variable named square_roots and assigns it the result of a list comprehension.
    • for x in numbers: This part sets up a loop that iterates through each number x in the numbers list.
    • math.sqrt(x): For each number in the list, this expression calculates the square root of x using the math.sqrt() function from the math module.
    • [math.sqrt(x) for x in numbers]: This is the list comprehension itself. It iterates through the numbers in the numbers list, calculates the square root of each number, and includes these square roots in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(square_roots): This line of code prints the square_roots list to the console.

Source Code

import math
numbers = [1, 4, 9, 16, 25]
square_roots = [math.sqrt(x) for x in numbers]
print(numbers)
print(square_roots)

Output

[1, 4, 9, 16, 25]
[1.0, 2.0, 3.0, 4.0, 5.0]

Example Programs