0

I am trying to minimize as much as possible my coding and trying to solve problems in different ways and i wrote this code which gets a list of numbers and it returns the square root of each one number in list

def square_roots(l):
    squareRoots = []
    result = [squareRoots.append(math.sqrt(i)) for i in l]
    return result

l=[1,2,3]
print(square_roots(l))

The only problem is that it returns [None, None, None] instead of the square root of each number in the array. What's wrong with it?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
jimmys
  • 11
  • 4
  • 5
    remove first line of your function then do `result = [math.sqrt(i) for i in l]` – Asocia Apr 25 '21 at 16:44
  • You are creating a list of the return value of an append method. The return value of append is None. The append method *did* add the results to the squareRoots list. If anything your return statement should `return squareRoots`. But embedding the loop in a list comprehension is unconventional at best. – RufusVS Apr 25 '21 at 16:45
  • @Asocia for that matter, how about simply: `return [math.sqrt(i) for i in l]` – RufusVS Apr 25 '21 at 16:46
  • what are the return type and value of `list.append`, would you say? – njzk2 Apr 25 '21 at 16:49
  • 1
    @RufusVS Yes, even better one is `print(*map(math.sqrt, l))` but I wanted to change as small code as possible. – Asocia Apr 25 '21 at 16:55

1 Answers1

1

list.append() (i.e. squareRoots.append()) returns None. Remove that part.

def square_roots(l):
    result = [math.sqrt(i) for i in l]
    return result

You might want to read Why does append() always return None in Python?

wjandrea
  • 28,235
  • 9
  • 60
  • 81