[python] Squaring all elements in a list

I am told to

Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.

At first, I had

def square(a):
    for i in a: print i**2

But this does not work since I'm printing, and not returning like I was asked. So I tried

    def square(a):
        for i in a: return i**2

But this only squares the last number of my array. How can I get it to square the whole list?

This question is related to python arrays return

The answer is


def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

import numpy as np
a = [2 ,3, 4]
np.square(a)

array = [1,2,3,4,5]
def square(array):
    result = map(lambda x: x * x,array)
    return list(result)
print(square(array))

One more map solution:

def square(a):
    return map(pow, a, [2]*len(a))

you can do

square_list =[i**2 for i in start_list]

which returns

[25, 9, 1, 4, 16]  

or, if the list already has values

square_list.extend([i**2 for i in start_list])  

which results in a list that looks like:

[25, 9, 1, 4, 16]  

Note: you don't want to do

square_list.append([i**2 for i in start_list])

as it literally adds a list to the original list, such as:

[_original_, _list_, _data_, [25, 9, 1, 4, 16]]

Use numpy.

import numpy as np
b = list(np.array(a)**2)

Use a list comprehension (this is the way to go in pure Python):

>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]

Or numpy (a well-established module):

>>> numpy.array([1, 2, 3, 4])**2
array([ 1,  4,  9, 16])

In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.


def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

so how would i do the square of numbers from 1-20 using the above function


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)