Square a list (or array?) of numbers in Python

user1936752 picture user1936752 · Feb 29, 2016 · Viewed 17.3k times · Source

I'm coming from a MATLAB background and this simple operation so far seems to be extremely complicated to implement in Python, according to the answers in other stacks. Typically, most answers use a for loop.

The best I've seen so far is

import numpy
start_list = [5, 3, 1, 2, 4]
b = list(numpy.array(start_list)**2)

Is there a simpler way?

Answer

bakkal picture bakkal · Feb 29, 2016

Note: Since we already have duplicates for the vanilla Python, list comprehensions and map and that I haven't found a duplicate to square a 1D numpy array, I thought I'd keep my original answer that uses numpy

numpy.square()

If you're coming from MATLAB to Python, you are definitely correct to try to use numpy for this. With numpy you can use numpy.square() which returns the element-wise square of the input:

>>> import numpy as np
>>> start_list = [5, 3, 1, 2, 4]
>>> np.square(start_list)
array([25,  9,  1,  4, 16])

numpy.power()

There is also a more generic numpy.power()

>>> np.power(start_list, 2)
array([25,  9,  1,  4, 16])