Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to return a list of squared integers

Tags:

python

list

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

like image 805
Alex Karpowitsch Avatar asked Feb 22 '11 14:02

Alex Karpowitsch


People also ask

How do you square data in python?

Because of this high usage Python provides three methods to square a number: they are: Using the Exponent Operator. Multiplying the number by itself (n*n) Using pow()

How do you square each element in an array python?

Square every element in NumPy array using numpy.square() np. square() calculates the square of every element in NumPy array. It does not modify the original NumPy array and returns the element-wise square of the input array.


2 Answers

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.

like image 54
Felix Kling Avatar answered Nov 07 '22 11:11

Felix Kling


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)
like image 45
kefeizhou Avatar answered Nov 07 '22 11:11

kefeizhou