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 ha
Use numpy.
import numpy as np
b = list(np.array(a)**2)
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
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]]
numbers = []
for i in range(10):numbers.append(i)
result = map(lambda x: x * x * x,numbers)
print(list(result))