Alex Karpowitsch
Alex Karpowitsch

Reputation: 673

Using python to return a list of squared integers

I'm looking to write a function that takes the integers within a list, such as [1, 2, 3], and returns a new list with the squared integers; [1, 4, 9]

How would I go about this?

PS - just before I was about to hit submit I noticed Chapter 14 of O'Reilly's 'Learning Python' seems to provide the explanation I'm looking for (Pg. 358, 4th Edition)

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

Upvotes: 7

Views: 30708

Answers (7)

swarna
swarna

Reputation: 1

You can use lambda with map to get this.

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

Upvotes: 0

phihag
phihag

Reputation: 287775

squared = lambda li: map(lambda x: x*x, li)

Upvotes: 6

eyquem
eyquem

Reputation: 27575

good remark of kefeizhou, but then there is no need of a generator function, a generator expression is right:

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

Upvotes: 0

kefeizhou
kefeizhou

Reputation: 6552

Besides lambda and list comprehensions, you can also use generators. List comprehension calculates all the squares when it's called, generators calculate each square as you iterate through the list. Generators are better when input size is large or when you're only using some 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)

Upvotes: 8

Felix Kling
Felix Kling

Reputation: 816334

You can (and should) use list comprehension:

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

map makes one function call per element and while lambda expressions are quite handy, using map + lambda is mostly slower than list comprehension.

Python Patterns - An Optimization Anecdote is worth a read.

Upvotes: 21

Senthil Kumaran
Senthil Kumaran

Reputation: 56823

You should know about map built-in which takes a function as the first argument and an iterable as the second and returns a list consisting of items acted upon by the function. For e.g.

>>> 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 of writing the sqr function above, namely using the nameless lambda having quirky syntax. (Beginners get confused looking for return stmt)

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

Apart from that you can use list comprehension too.

result = [x*x for x in range(1,10)]

Upvotes: 2

FogleBird
FogleBird

Reputation: 76762

a = [1, 2, 3]
b = [x ** 2 for x in a]

Upvotes: 1

Related Questions