Using python to return a list of integers

I want to write a function that takes integers in a list, such as [1, 2, 3], and returns a new list with square integers; [1, 4, 9]

How can i do this?

PS - just before I was about to get into submit, I noticed that chapter 14 of O'Reilly's “Learning Python” seems to give the explanation I'm looking for (p. 358, 4th edition).

But I'm still curious to know what other solutions are possible.

+4
source share
7 answers

You can (and should) use list comprehension :

squared = [x**2 for x in lst] 

map makes one function call for each element, and lambda expressions are very convenient, using map + lambda is generally slower than list comprehension.

Python Patterns - An optimization joke deserves to be read.

+17
source

Besides the concepts of lambda and list, you can also use generators. List accounting calculates all squares when it is called, generators calculate each square when repeating through the list. Generators are better if the input size is large or when you use only the initial part of the results.

 def generate_squares(a): for x in a: yield x**2 # this is equivalent to above b = (x**2 for x in a) 
+9
source
 squared = lambda li: map(lambda x: x*x, li) 
+6
source

You should be aware of the built-in map , which takes a function as the first argument and is iterable as the second and returns a list of the elements the function acts on. For instance,

 >>> def sqr(x): ... return x*x ... >>> map(sqr,range(1,10)) [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> 

There is a better way to write the sqr function above, namely using an unnamed lambda with fancy syntax. (Beginners get confused looking for stmt return)

 >>> map(lambda x: x*x,range(1,10)) [1, 4, 9, 16, 25, 36, 49, 64, 81] 

In addition, you can also use list comprehension.

 result = [x*x for x in range(1,10)] 
+2
source
 a = [1, 2, 3] b = [x ** 2 for x in a] 
+1
source

A good note is kefeizhou, but then there is no need for a generator function, the correct expression for the generator:

 for sq in (x*x for x in li): # do 
0
source

You can use lambda with map to get this.

 lst=(3,8,6) sqrs=map(lambda x:x**2,lst) print sqrs 
0
source

Source: https://habr.com/ru/post/1340797/


All Articles