How To Subtract In Python

Python is a versatile and widely-used programming language that offers a wide variety of features and functionalities.

One of the basic operations that you need to learn when getting started with Python is subtraction. In this tutorial, we will explore different ways to perform subtraction in Python, whether it be with integers, floating-point numbers, or even lists and arrays.

Step 1: Basic Subtraction with Integers and Floating-Point Numbers

Python provides a straightforward way to perform subtraction with integers and floating-point numbers. Simply use the minus (-) operator between two numbers, like this:

Let’s create a simple Python script to perform subtraction and print the result:

Output:

The result of the subtraction is: 5

Note that this method also works seamlessly with floating-point numbers:

Output:

The result of the subtraction is: 8.8

Step 2: Subtracting Items in a List or Tuple

Python allows you to perform list or tuple subtraction using the built-in zip() function and list comprehensions. Here’s an example of how to do it:

Output:

The result of the list subtraction is: [7, 13, 20, 35]

This method works with tuples as well:

Output:

The result of the tuple subtraction is: [7, 13, 20, 35]

Step 3: Subtracting Items in NumPy Arrays

If you are working with larger arrays or matrices, it is recommended to use the NumPy library for better performance. Let’s see how to perform subtraction using NumPy arrays:

First, you need to install the NumPy library if you haven’t already:

Now, let’s perform array subtraction using NumPy:

Output:

The result of the NumPy array subtraction is: [ 7 13 20 35]

Full Code

Conclusion

In this tutorial, we learned how to perform subtraction in Python using various data types, such as integers, floating-point numbers, lists, tuples, and NumPy arrays. This basic operation is essential to many programming tasks, so make sure you understand these examples and adapt them to fit your specific use case.