12

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arpan Das
  • 321
  • 1
  • 3
  • 9

7 Answers7

21

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
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
15

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]
gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • As someone used to brace based programming rather than indentation based, I must say that single tab changing where the function returns from is something I find horribly unintuitive. – Pharap Feb 01 '16 at 10:20
  • But you still indent your code even if your using braces, don't you? – Matthias Feb 01 '16 at 12:18
6

We even use result? You can use a list comprehension to generate your result which you then return. I'm not sure why you passed result as a variable into the function, since it is not used.

Also, having return result inside your loop means the function returns the value on the first iteration, so it just returns the square of the first number in the list.

import math

def square(x):
    return [math.pow(y, 2) for y in x]

>>> print(square([1,2,3]))
[1.0, 4.0, 9.0]
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • Well, it could be seen as the initial value, for example. Perhaps OP intended `square([1,2,3],[100,200,300])` to return `[100,200,300,1,4,9]`. – muru Feb 01 '16 at 03:43
3

You should return outside the for loop. Otherwise, it will stop after first iteration.

def square(x):
    result=[]
    for y in x:
        result.append(math.pow(y,2.0)) # add to list after calculation
    return result 

print(square([1,2,3])
hamaney
  • 454
  • 7
  • 16
Munir
  • 3,442
  • 3
  • 19
  • 29
3

You might be interested in using yield

def square(x):
    for y in x:
        yield math.pow(y, 2.0)

that way you can either call

for sq in square(x):
    ...

which won't generate the entire list of squares at once but rather one element per iteration, or use list(square(x)) to obtain the full list on demand.

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
3

This is a fun opportunity to use a slightly more functional style:

import math
map(lambda x:(math.pow(x,2)), [1,2,3])

This uses the map function, which takes a list and a function, and returns a new list where that function has been applied individually to each member of the list. In this case, it applies the math.pow(x,2) function to each member of the list, where each number is x.

Notice that map(lambda x:(math.pow(x,2)), [1,2,3]) returns an iterable, which is really convenient, but if you need to get a list back just wrap the entire statement in list().

0

your code doesn't make sense anywhere. syntax error at the end missing the closing bracket for the print, return call inside the for loop meaning it only executes once, and result.append is a function not a constructor sp the correct call is

result.append(math.pow(y,2))

the only thing that is not an issue is the passing of the list which is your question, the function is receiving the whole list if you do

def f(a):
    print a
f([1,2,3])

out

[1,2,3,]
user2255757
  • 756
  • 1
  • 6
  • 24