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
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()
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With