How to get Square of all array values in Python

← PrevNext →

Let us assume, I have an array of values (numbers) and I want to get the square of each array value, without running a loop like "for" etc. I can do this using recursion in Python.

A recursion refers to a function calling itself repeatedly till it meets a certain condition. It has to stop at one point.

So we are going use recursion in Python to get the Square of each value in an array.

Get Square of a number in Python

But first, let us see how to get the square of a number in Python.

def square(number):
  return number * number

result = square(4)
print (result)	 # Output: 16

If its a single number, we can simply multiply the number to itself to get the square.

Using Recursion in Python

If there's an array of numbers, we can use recursion to get the square of all the values. For example,

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

arr = [2,4,6]
result = square(arr)    
print (result)	# Output: [4, 16, 36]

I am using power operator in the above example, to get the square of a value. ** is the called the power operator.

So, if you want get the square of 8 using the "power operator" (**), you can do something like this

def square():
  return [8 ** 2]

result = square()    
print (result)

➡️ In-addition, you can use Python's built-in pow() function to get the square of all numbers in an array without using loop. See the next article.

← PreviousNext →