Use list comprehension (this is a way to switch to pure Python):
>>> l = [1, 2, 3, 4] >>> [i**2 for i in l] [1, 4, 9, 16]
Or numpy (well-installed module):
>>> numpy.array([1, 2, 3, 4])**2 array([ 1, 4, 9, 16])
In numpy mathematical operations on arrays are performed by element by default. This is why you can **2 create an entire array.
Other possible solutions would be map , but in this case I will really go for understanding the list. This is Pythonic :) and a map based solution that requires lambda slower than LC .
Jan-Philip Gehrcke
source share