Combining all items in a list

I was told

Write a function, square (a), which takes an array of, a, numbers and returns an array containing each of the values ​​of the square.

I first had

def square(a): for i in a: print i**2 

But this does not work, since I print and do not return, as I was asked. So I tried

  def square(a): for i in a: return i**2 

But this is only the square of the last number of my array. How can I get it to fill the whole list?

+7
source share
8 answers

You can use 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 can use a generator. It will not return the list, but you can still iterate over it, and since you do not need to select the whole new list, it is probably more economical in area than other parameters:

 def square(list): for i in list: yield i ** 2 

Or you can make the boring old for -loop, although it’s not as idiomatic as some Python programmers would prefer:

 def square(list): ret = [] for i in list: ret.append(i ** 2) return ret 
+20
source

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 .

+18
source
 def square(a): squares = [] for i in a: squares.append(i**2) return squares 
+1
source

Use numpy.

 import numpy as np b = list(np.array(a)**2) 
+1
source
 import numpy as np a = [2 ,3, 4] np.square(a) 
+1
source

Another map solution:

 def square(a): return map(pow, a, [2]*len(a)) 
0
source
 def square(a): squares = [] for i in a: squares.append(i**2) return squares 

so how would I make a square of numbers from 1 to 20 using the above function

0
source

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 returns

 [25, 9, 1, 4, 16] 

Note: you do not want to do

 square_list.append([i**2 for i in start_list]) 

when it returns the list in the list:

 [[25, 9, 1, 4, 16]] 
0
source

All Articles