Search code examples
pythonlistsquare-root

Python- Square Root of list


Taking the square root of each number in a list.

For this problem in the sqrt_list function:

  1. Take the square root of each item in the list,
  2. Store each squared item in another list, and
  3. Return this list.
alist = [11,22,33]
def sqrt_list(alist):
    ret = []
    for i in alist:
        ret.append(i %)
    return ret

Solution

  • Maybe this?

    # Use this import for all examples
    from math import sqrt
    
    old = [1,2]
    new = [sqrt(x) for x in old]
    

    Function form

    def sqrt_list(old):
        return [sqrt(x) for x in old]
    

    or

    def sqrt_list(old):
        new_list = []
    
        for i in old:
            new_list.append(sqrt(i))
    
        return new_list
    

    Where:

    print(sqrt_list([11, 22, 33]))
    

    outputs:

    [3.3166247903554, 4.69041575982343, 5.744562646538029]