Squaring all elements in a list
You could use a list comprehension:
def square(list):
return [i ** 2 for i in list]
Or you could map
it:
def square(list):
return map(lambda x: x ** 2, list)
Or you could use a generator. It won't return a list, but you can still iterate through it, and since you don't have to allocate an entire new list, it is possibly more space-efficient than the other options:
def square(list):
for i in list:
yield i ** 2
Or you can do the boring old for
-loop, though this is not as idiomatic as some Python programmers would prefer:
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
import numpy as np
a = [2 ,3, 4]
np.square(a)
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 lambda
s is slower than LC.