89DEVs

How to subtract in Python?

How to subtract in Python?

To subtract in Python, use the subtraction (-) operator.

subtract integers in Python

If all values are integers, the result will be returned as an integer as well. # subtract integers a, b = 5, 1 print(a - b) In this example, the subtraction is done within the print() function. The result is returned as integer and printed. 4 Of course it is possible to subtract more than two numbers. # subtract more numbers a, b, c, d = 10, 5, 2, 1 result = a - b - c - d print(result) In this example, three numbers are subtracted from a. The result is returned and printed. 10 - 5 - 2 - 1 = 2 2

subtract float values

If at least one of the operands is a float value, the result is returned as a float value. # subtract float values a, b = 5.2, 1 print(a - b) The result is returned as float value and printed. Use the round() method to round to the next integer. 4.2

subtract complex numbers

If the operands are complex numbers, the result will be returned as a complex number. # subtract complex numbers a, b = complex(9, 8), complex(1, 4) print(a - b) The complex numbers are subtracted and the result is returned as a complex number. (8+4j)

subtract sets

If we subtract sets using the - operator, the elements in the second sets are removed from the first list. # subtract sets mySet1 = {1,2,3,4,5,6,7,8,9,0} mySet2 = {1,3,5,7,9} print(mySet1 - mySet2) All elements in mySet2 are removed from mySet1. This leaves only the unique elements of mySet1. {0, 2, 4, 6, 8} To perform the same operation for lists, convert the list to sets first. # subtract lists mySet1 = set([1,2,3,4,5,6,7,8,9,0]) mySet2 = set([1,3,5,7,9]) print(list(mySet1 - mySet2)) The lists are converted into sets, then the sets are subtracted and finally, the set is converted into a list and printed. [0, 2, 4, 6, 8] While this option works, it has some limitations. For example sets() only contains unique elements. If a list with duplicates is converted into a set, each element is only added once.

subtract in numpy

To subtract in numpy, use the subtract() method as shown below. # subtract in numpy import numpy as np a, b = 6, 1 result = np.subtract(a, b) print(result) In this example, numpy is imported as np. Then the np.subtract() method is used to subtract a and b. Finally the result is printed. 5 By using numpy it is possible to subtract multiple arrays. However, the shape of the arrays has to match. # subtract lists using numpy import numpy as np myArray1 = np.array([1,2,3,4,5,6,7,8,9,0]) myArray2 = np.array([1,3,5,7,9,4,5,5,4,0]) result = np.subtract(myArray1, myArray2) print(result) In this example, the numpy.subtract() method is used to subtract each element of the two arrays. [ 0 -1 -2 -3 -4 2 2 3 5 0]

                
        

Summary


Click to jump to section