views:

180

answers:

6
def fun1(a):

    for i in range(len(a)):
        a[i] = a[i] * a[i]
    return a
+12  A: 

It takes an array as parameter and returns the same array with each member squared.

EDIT:

Since you modified your question from 'What does this function do' to 'What is some code to execute this function', here is an example:

def fun1(a):
    for i in range(len(a)):
        a[i] = a[i] * a[i]
    return a

test1 = [1,2,3,4,5]
print 'Original list', test1
test2 = fun1(test1)
print 'Result', test2
print 'Original list', test1

The output will be:

Original list [1, 2, 3, 4, 5]
Result [1, 4, 9, 16, 25]
Original list [1, 4, 9, 16, 25]

Because the function modifies the list in place, test1 is also modified.

Andre Miller
and it can also be written as: [item*item for item in a]
Anders Westrup
It's also worth mentioning that it actually modifies the variable that was passed to the function. If you apply it more than once to the same variable you will get a different result each time.
Ben James
+2  A: 

it multiplies each element of the array "a" with itself and stores the results back in the array.

thijs
+2  A: 

a is passed as a list , I assume.

It squares each element of the list and returns the list.

TIMEX
+3  A: 

It will go through your List and multiply each value by itself.

Example

a = [ 1, 2, 3, 4, 5, 6 ]

After that function a would look like this:

a = [ 1, 4, 9, 16, 25, 36 ]
Filip Ekberg
In Python a list uses square brackets
Andre Miller
Thanks, corrected it.
Filip Ekberg
+1  A: 

It squares every element in the input array and returns the squared array.

So with a = [1,2,3,4,5]

result is: [1,4,9,16,25]

bruno conde
+3  A: 

It's a trivial function that could be replaced with the one-liner:

a = [x*x for x in a]
Ben James
That probably just confuses him.
Filip Ekberg
I suspect that for a beginner, this will be even more confusing.
Chris Lutz
I don't think it's confusing. (Simple) list comprehensions were not at all confusing for me as a Python beginner.
Ben James
Also, as demonstrated by Andre's example, it's not exactly identical. `a = fun1(a)` is identical to `a = [x*x for x in a]` but `b = fun1(a)` is not the same as `b = [x*x for x in a]` (this should probably be considered a bug in `fun1` ).
Chris Lutz
Chris, I think you're taking my example as general when it wasn't meant to be. There's a reason why my example starts with `a =`.
Ben James