Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list as an input of a function in Python

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?

like image 366
Arpan Das Avatar asked Jan 31 '16 23:01

Arpan Das


1 Answers

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]
like image 51
gtlambert Avatar answered Sep 27 '22 18:09

gtlambert