Python // operator – Floor Based Division

The // operator in Python 3 is used to perform floor-based division.

This means that a // b first divides a by b and gets the integer quotient, while discarding the remainder. This means that the result of a//b is always an integer.

Python // Operator Examples

Here are a few examples to illustrate the same:

>>> 2 // 3
0
>>> 1.3 // 2
0.0
>>> 1.3 // 1.0
1.0
>>> 3.4 // 1.1
3.0
>>> 3.4 // 1.2
2.0
>>> -1//2
-1
>>> -6 // 2
-3
>>> -6 // -3
2

This shows how the // operator performs the floor based division, by only considering the integer part of the division, even for floating-point numbers.

Performing this operation on unsupported types (like lists and strings), will result in a TypeError, as is the same for any other arithmetic operator.


Overloading the // Operator

// refers to the __floordiv__() operator by default, so you can perform operator overloading by overriding this method (operator.__floordiv__(a, b))

Here is an example that overloads the // method for integer lists having the same length, by performing individual floor-based division on every pair of elements.

So the two integer lists [3, 4, 5] and [2, 2, 1] will give [3//2, 4//2, 5//1], which is simply the list [1, 2, 5].

import operator

class MyClass():
    def __init__(self, a):
        self.a = a

    def __floordiv__(self, b):
        if isinstance(self.a, list) and isinstance(b.a, list) and len(self.a) == len(b.a):
            result = []
            # Overload // operator for Integer lists
            for i, j in zip(self.a, b.a):
                result.append(i // j)
            return result
        else:
            # Perform Default // operation otherwise
            return operator.__floordiv__(self.a, b.a)

m = MyClass([3, 4, 5])
n = MyClass([2, 2, 1])

print(m // n)

Output

[1, 2, 5]

Conclusion

In this article, we learned about the // floor division operator. We also learned about performing operator overloading on this by implementing operator.__floordiv__(a, b).

References