Python pow() function - Get Square of all numbers in an array

← PrevNext →

In my previous article I have explained how to use the power operator ** in python to get square of all numbers in an array using recursion. In this article I'll show you how to use Python's built-in pow() (power) function to get the square of all the values in an array.

pow() function Syntax

pow(base, exponent)

The "pow()" function (or the power function) returns the value of x to the power of y.

The "pow()" function takes three arguments. All the arguments must be a numeric value.

base: A number to be raised.

exponent: A number as the exponent or the power the base value will be raised.

modulus: A number as the modulus. This is optional.

For example, if you want to get the square of 4, the base value will be "4" and the exponent will be "2". So, its 4 to the power 2. And this is how you can use the function in python.

print (pow(4, 2))  # Output: 16

Get the square of all numbers in an array

Now, let's see how we can apply the "pow()" function in Python to get the square of all the numbers in an array.

Here, I am using the recursion method to get the square value of each number in the array.

Note: A recursion refers to a function calling itself repeatedly till it meets a certain condition.

def square(number):
  return [pow(number[0], 2)] + square (number[1:]) if number else []

arr = [9,12,8]
result = square(arr)    # call sqaure() function
print (result)          # Output: [81, 144, 64]

I have defined a function named "square" in the beginning. The fuction takes a parameter (an argument) in the form of a array. The function calls itself (its a recursion function) till it reaches the last number. Finally, it returns the result.

Its calculating "square" of values. Its obvious that it will expect numbers only. So, make sure the array has numbers only.

← PreviousNext →