Search code examples
pythonsquare

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


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?


Solution

  • The most readable is probably a list comprehension:

    start_list = [5, 3, 1, 2, 4]
    b = [x**2 for x in start_list]
    

    If you're the functional type, you'll like map:

    b = map(lambda x: x**2, start_list)  # wrap with list() in Python3