I am using Python, and I have a function which takes a list as the argument. For example, I am using the following syntax,
def square(x,result= []):
for y in x:
result.append=math.pow(y,2.0)
return result
print(square([1,2,3]))
and the output is [1]
only where I am supposed to get [1,4,9]
.
What am I doing wrong?
You are currently returning a value from your function in the first iteration of your for
loop. Because of this, the second and third iteration of your for
loop never take place. You need to move your return
statement outside of the loop as follows:
import math
def square(x):
result = []
for y in x:
result.append(math.pow(y,2.0))
return result
print(square([1,2,3]))
Output
[1.0, 4.0, 9.0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With