+

# Division without remainder and the // operator in Python

The // operator in Python 3 is used to perform division without remainder.

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

## Examples

Here are some examples to illustrate the same:

< / ins>

& gt; & gt; & gt; 2 // 3 0 & gt; & gt; & gt; 1.3 // 2 0.0 & gt; & gt; & gt; 1.3 // 1.0 1.0 & gt; & gt; & gt; 3.4 // 1.1 3.0 & gt; & gt; & gt; 3.4 // 1.2 2.0 & gt; & gt; & gt; -1 // 2 -1 & gt; & gt; & gt; -6 // 2 -3 & gt; & gt; & gt; -6 // -3 2

This shows how the // operator performs division based on gender, considering only the integer portion of the division, even for floating point numbers.

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

< br>

// defaults to __floordiv __ () , so you can overload the operator by overriding this method ( operator .__ floordiv __ (a, b) )

Here`s an example that overloads the // for integer lists of the same length, doing individual division based on gender for each pair of elements.

Thus, two integer lists are [3, 4, 5] and [ 2, 2, 1] will give [3 // 2, 4 // 2, 5 // 1] , which is just a list [1, 2, 5] < / code>.

import operator class MyClass (): def __init __ (self, a): self.a = a def __floordiv __ (self, b): if isinstance (self.a, list) an d isinstance (ba, list) and len (self.a) == len (ba): result = [] # Overload // operator for Integer lists for i, j in zip (self.a, ba): result.append (i // j) return result else: # Perform Default // operation otherwise return operator .__ floordiv __ (self.a, ba) m = MyClass ([3, 4, 5]) n = MyClass ([2, 2, 1 ]) print (m // n)

Output

[1, 2, 5]
< h3> Output