What does Python's //
operator do?
How is it different from the /
operator?
/
operatorThe /
operator is the division operator in Python.
When /
is used between two numbers, you'll always get the exact (as exact as Python can manage) result back:
>>> 5 / 2
2.5
Unlike some programming languages, /
in Python does not act any differently when used between integers; in Python 3 that is.
In Python 2, division between two integers would would the result downward to the nearest integer:
>>> 5 / 2 # Python 2
2
But in Python 3, division between two integers always returns a floating point number with the exact result:
>>> 4 / 2
2.0
//
operator between integersThe //
operator is the floor division operator in Python.
When //
is used between two integers, you'll always get an integer back:
>>> 5 // 2
2
The //
operator provides divides while rounding the result down to the nearest integer.
This is often called integer division or floor division.
When using //
with a floating point number, you'll get a floating point number back:
>>> 5.0 // 2
2.0
But, just as with integers, that floating point number will also be rounded down to the nearest integer.
//
in Python?If you've ever seen code like this:
>>> n = 5
>>> int(n / 2)
2
Then you've likely witnessed an opportunity to use the //
operator.
If you're dividing and then immediately converting the result to an integer, you could probably use the //
operator instead.
In this split_in_half
function, we're using the int
function to make sure the mid_point
value is an integer:
def split_in_half(sequence):
"""Return two halves of given sequence (list, string, etc)."""
mid_point = int(len(sequence) / 2)
return sequence[:mid_point], sequence[mid_point:]
The numbers we're dividing are both integers, so we could use //
to force an integer result:
def split_in_half(sequence):
"""Return two halves of given sequence (list, string, etc)."""
mid_point = len(sequence) // 2
return sequence[:mid_point], sequence[mid_point:]
This is a bit more efficient than dividing to get an exact floating point number and then flooring that floating point number to get back to an integer.
//
always rounds downBefore you go about replacing all the uses of int(a / b)
in your code with a // b
, you should note that these two act differently when the result of the division is a negative number:
Let's say we divide and the result is -2.5
:
>>> a = -5
>>> b = 2
>>> a / 2
-2.5
When using /
and int
, we'll end up with -2
but when dividing with //
we'll get -3
instead:
>>> int(a / 2)
-2
>>> a // 2
-3
The //
operator always rounds down.
It acts less like the built-in int
function and more like math.floor
:
>>> from math import floor
>>> floor(a / 2)
-3
>>> a // 2
-3
Also remember that a // b
returns a floating point number when either a
or b
are floating point numbers.
>>> a = 52.0
>>> b = 4
>>> a // b
13.0
So you'll most likely want to stick to using //
only for division between positive integers.
divmod
insteadWhat if you want both integer division (with //
) and the remainder of that division (with %
):
>>> duration = 500
>>> minutes = duration // 60
>>> seconds = duration % 60
>>> print(f"{minutes}:{seconds}")
8:20
Instead of using //
and %
separately, you could use the divmod
function to get both results at once:
>>> duration = 500
>>> minutes, seconds = divmod(duration, 60)
>>> print(f"{minutes}:{seconds}")
8:20
In theory, this could be optimized to perform both operations at once, but in practice CPython doesn't perform that optimization so this is primarily about readability.
Sometimes divmod
can make for considerably more readable code.
For example here we're using //
and %
cleverly to get hours, minutes, and seconds:
>>> duration = 9907
>>> hours = duration // (60 * 60)
>>> minutes = (duration // 60) % 60
>>> seconds = duration % 60
>>> print(f"{hours}:{minutes:02d}:{seconds:02d}")
2:46:07
But we could use divmod
twice instead:
>>> duration = 9907
>>> minutes, seconds = divmod(duration, 60)
>>> hours, minutes = divmod(minutes, 60)
>>> print(f"{hours}:{minutes:02d}:{seconds:02d}")
2:46:07
I find that divmod
approach much clearer than the alternative uses of //
and %
.
If you need both the quotient (to use a math term) and the remainder of your division, consider using divmod
.
Note: if you're curious about that :02d
syntax above, see zero-padding in f-strings.
//
for integer divisionFor most uses of division in Python, you'll likely use /
because precise answers are often desirable:
>>> amount = 67
>>> groups = 9
>>> per_portion = amount / groups
>>> per_portion
7.444444444444445
But in rare moments when you want floor division (a.k.a. integer division) you'll want the //
operator.
>>> amount = 67
>>> groups = 9
>>> minimum_per_group = amount // groups
>>> minimum_per_group
7
If you want both a remainder %
and integer division //
, also keep Python's divmod
function in mind.
>>> duration = 784
>>> minutes, seconds = divmod(duration, 60)
>>> print(f"{minutes}m{seconds}s")
13m4s
Need to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.
Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.