Why not side-step the problem altogether?
def square(vals):
return [v*v for v in vals]
Edit: The first problem, as several people have pointed out, is that you are short-circuiting your for
loop. Your return
should come after the loop, not in it.
The next problem is your use of list.append
- you need to call it, not assign to it, ie result.append(y*y)
. result.append = y*y
instead overwrites the method with a numeric value, probably throwing an error the next time you try to call it.
Once you fix that, you will find another less obvious error occurs if you call your function repeatedly:
print(square([1,2,3]) # => [1, 4, 9]
print(square([1,2,3]) # => [1, 4, 9, 1, 4, 9]
Because you pass a mutable item (a list) as a default, all further use of that default item points back to the same original list.
Instead, try
def square(vals, result=None):
if result is None:
result = []
result.extend(v*v for v in vals)
return result