What is the reason for having '//' in Python? [duplicate]
In Python 3, they made the
/ operator do a floating-point division, and added the
// operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the
/ operator was simply integer division, unless one of the operands was already a floating point number.
In Python 2.X:
10/33# To get a floating point number from integer division:10.0/33.3333333333333335float(10)/33.3333333333333335
In Python 3:
For further reference, see PEP238.
// is unconditionally "flooring division", e.g:
As you see, even though both operands are
// still floors -- so you always know securely what it's going to do.
/ may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:
$ python2.6 -Qold -c 'print 2/3'0$ python2.6 -Qnew -c 'print 2/3'0.666666666667
As you see, single
/ may floor, or it may return a float, based on completely non-local issues, up to and including the value of the
So, if and when you know you want flooring, always use
//, which guarantees it. If and when you know you don't want flooring, slap a
float() around other operand and use
/. Any other combination, and you're at the mercy of version, imports, and flags!-)
To complement these other answers, the
// operator also offers significant (3x) performance benefits over
/, presuming you want integer division.
$ python -m timeit '20.5 // 2'100,000,000 loops, best of 3: 14.9 nsec per loop$ python -m timeit '20.5 / 2' 10,000,000 loops, best of 3: 48.4 nsec per loop$ python -m timeit '20 / 2' 10,000,000 loops, best of 3: 43.0 nsec per loop$ python -m timeit '20 // 2'100,000,000 loops, best of 3: 14.4 nsec per loop