Squaring in Python: 4 Ways How to Square a Number in Python

This article was first published on Python - Better Data Science , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Squaring in Python: 4 Ways How to Square a Number in Python

If you want to square a number in Python, well, you have options. There are numerous ways and approaches to Python squaring, and today we'll explore the four most common. You'll also learn how to square Python lists in three distinct ways, but more on that later.

Let's get started with the first Python squaring approach – by using the exponent operator (**).

Table of contents:

  • Square a Python Number Using the Exponent Operator (**)
  • Python's Math Library – Square Numbers With the pow() Function
  • Square a Python Number with Simple Multiplication
  • Numpy – How to Square a Number with Numpy's square() Function
  • Bonus: 3 Ways to Square a Python List
  • Summing up Python Squaring

Square a Python Number Using the Exponent Operator (**)

The asterisk operator in Python – ** – allows you to raise a number to any exponent. It's also used to unpack dictionaries, but that's a topic for another time.

On the left side of the operator, you have the number you want to raise to an exponent, and on the right side, you have the exponent itself. For example, if you want to square the number 10, you would write 10**2 – it's that easy.

Let's take a look at a couple of examples:

a = 5
b = 15
c = 8.65
d = -10

# Method #1 - The exponent operator (**)
a_squared = a**2
b_squared = b**2
c_squared = c**2
d_squared = d**2

# Print
print("Method #1 - The exponent operator (**)")
print("--------------------------------------------------")
print(f"{a} squared = {a_squared}")
print(f"{b} squared = {b_squared}")
print(f"{c} squared = {c_squared}")
print(f"{d} squared = {d_squared}")

Below you'll see the output of the code cell:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 1 – Squaring method 1 (image by author)

And that's how you can square, or raise a number to the second power by using the asterisk operator.

But what if you want to change the exponent? Simply change the number on the right side of the operator:

print("Method #1 - The exponent operator (**) (2)")
print("--------------------------------------------------")
print(f"{a} to the power of 3 = {a**3}")
print(f"{d} to the power of 5 = {d**5}")

Code output:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 2 – Squaring method 1 (2) (image by author)

One down, three to go.

Python's Math Library – Square Numbers With the pow() Function

The math module is built into Python and packs excellent support for mathematical functions. One of these functions is pow(), and it accepts two arguments:

  • x – The number you want to square or raise to an exponent.
  • y – The exponent.

Let's modify the code snippet from earlier to leverage the math module instead:

import math


a = 5
b = 15
c = 8.65
d = -10

# Method #2 - math.pow() function
a_squared = math.pow(a, 2)
b_squared = math.pow(b, 2)
c_squared = math.pow(c, 2)
d_squared = math.pow(d, 2)

# Print
print("Method #2 - math.pow() function")
print("--------------------------------------------------")
print(f"{a} squared = {a_squared}")
print(f"{b} squared = {b_squared}")
print(f"{c} squared = {c_squared}")
print(f"{d} squared = {d_squared}")

Here's the output:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 3 – Squaring method 2 (image by author)

The output is nearly identical to what we had before, but the math module converts everything to a floating point number, even if there's no need for it. Keep that in mind, as it's an additional casting step if you explicitly want integers.

As you would imagine, raising a number to any other exponent is as easy as changing the second argument value:  

print("Method #2 - math.pow() function (2)")
print("--------------------------------------------------")
print(f"{a} to the power of 3 = {math.pow(a, 3)}")
print(f"{d} to the power of 5 = {math.pow(d, 5)}")

Code output:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 4 – Squaring method 2 (2) (image by author)

Let's take a look at another, more manual approach to Python squaring.

Square a Python Number with Simple Multiplication

There's no one stopping you from implementing squaring in Python by multiplying the number with itself. However, this approach isn't scalable. It's fine if you want to simply square a number, but what if you want to raise the number to a power of ten?

Here's an example of how to square a number by multiplying it by itself:

a = 5
b = 15
c = 8.65
d = -10

# Method #3 - Multiplication
a_squared = a * a
b_squared = b * b
c_squared = c * c
d_squared = d * d

# Print
print("Method #3 - Multiplication")
print("--------------------------------------------------")
print(f"{a} squared = {a_squared}")
print(f"{b} squared = {b_squared}")
print(f"{c} squared = {c_squared}")
print(f"{d} squared = {d_squared}")

The results are identical to what we had in the first example:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 5 – Squaring method 3 (image by author)

If you want to raise a number to some other exponent, this approach quickly falls short. You need to repeat the multiplication operation many times, which isn't convenient:

print("Method #3 - Multiplication (2)")
print("--------------------------------------------------")
print(f"{a} to the power of 3 = {a * a * a}")
print(f"{d} to the power of 5 = {d * d * d * d * d}")

Code output:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 6 – Squaring method 3 (2) (image by author)

The results are still correct, but they're prone to errors that wouldn't happen if you were using any other approach.

Numpy – How to Square a Number with Numpy's square() Function

Python's Numpy library is a holy grail for data scientists. It allows for effortless work with N-dimensional arrays, but it can also handle scalars.

Numpy's square() function will raise any number or an array to the power of two. Let's see how to apply it to our previous code snippet:

import numpy as np


a = 5
b = 15
c = 8.65
d = -10

# Method #4 - Numpy
a_squared = np.square(a)
b_squared = np.square(b)
c_squared = np.square(c)
d_squared = np.square(d)

# Print
print("Method #4 - Numpy")
print("--------------------------------------------------")
print(f"{a} squared = {a_squared}")
print(f"{b} squared = {b_squared}")
print(f"{c} squared = {c_squared}")
print(f"{d} squared = {d_squared}")

The results are displayed below:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 7 – Squaring method 4 (image by author)

The one limitation of the square() function is that it only raises a number/array to the power of two. If you need a different exponent, use the power() function instead:

print("Method #4 - Numpy (2)")
print("--------------------------------------------------")
print(f"{a} to the power of 3 = {np.power(a, 3)}")
print(f"{d} to the power of 5 = {np.power(d, 5)}")

Code output.

Squaring in Python: 4 Ways How to Square a Number in Python
Image 8 – Squaring method 5 (image by author)

And that does it for squaring Python numbers. Let's see how to do the same to Python lists next.

Bonus: 3 Ways to Square a Python List

As a data scientist, you'll spend a lot of time working with N-dimensional arrays. Knowing how to apply different operations to them, such as squaring each array item is both practical and time-saving. This section will show you three ways to square a Python list.

Method 1 – Looping

The first, and the most inefficient one is looping. We have two Python lists, the first one stores the numbers, and the second will store the squared numbers. We then iterate over the first list, square each number, and append it to the second one.

Here's the code:

arr = [5, 15, 8.65, -10]
squared = []


# Method 1 - Looping
for num in arr:
    squared.append(num**2)
    
# Print
print("Method #1 - Looping")
print("--------------------------------------------------")
print(squared)

And here's the output:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 9 – Squaring a Python list with looping (image by author)

Iterating over an array one item at a time isn't efficient. There are more convenient and practical approaches, such as list comprehension.

Method 2 – List comprehension

With list comprehensions, you declare a second list as a result of some operation applied element-wise on the first one. Here we want to square each item, but the possibilities are endless.

Take a look at the following code snippet:

arr = [5, 15, 8.65, -10]


# Method 2 - List comprehensions
squared = [num**2 for num in arr]

    
# Print
print("Method #2 - List comprehensions")
print("--------------------------------------------------")
print(squared)

The results are identical, but now take one line of code less:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 10 – Squaring a Python list with list comprehensions (image by author)

Let's switch gears and discuss you can square an array in Numpy.

Method 3 – Numpy

Remember the square() function from the previous section? You can also use it to square individual array items. Numpy automatically infers if a single number or an array has been passed as an argument:

arr = np.array([5, 15, 8.65, -10])


# Method 3 - Numpy
squared = np.square(arr)
    
# Print
print("Method #3 - Numpy")
print("--------------------------------------------------")
print(squared)

Here are the results:

Squaring in Python: 4 Ways How to Square a Number in Python
Image 11 – Squaring a Python list with Numpy (image by author)

The Numpy array elements now have specific types – numpy.float64 – so that's why you see somewhat different formatting when the array is printed.

And that's how easy it is to square a number or a list of numbers in Python. Let's make a short recap next.


Summing up Python Squaring

It's almost impossible to take a beginner's programming challenge without being asked to write a program that squares an integer and prints the result.

Now you know multiple approaches to squaring any type of number, and even arrays in Python. You've also learned how to raise a number to any exponent, and why some approaches work better than others.

Stay tuned to the blog if you want to learn the opposite operation – square roots – and what options you have in Python programming language.

Stay connected

To leave a comment for the author, please follow the link and comment on their blog: Python - Better Data Science .

Want to share your content on python-bloggers? click here.