Python floordiv: How the // Operator Works
python **floordiv**: Learn how Python's floor division operator // works with integers and floats, including negative numbers, modulo relationships, and common pitfalls.
python floordiv requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
Python floordiv, performed with the // operator, returns the largest integer less than or equal to the division result. This is different from truncation, which rounds toward zero. Many developers discover this difference only when they divide negative numbers.
The // Operator and Its Behavior
The // operator performs floor division on its operands. For two integers, it returns an integer; for floats, it returns a float that is the floor of the division result.
print(7 // 2) # 3 print(-7 // 2) # -4 print(7.0 // 2) # 3.0
In the first example, 7 / 2 equals 3.5, and the floor is 3. In the second, -7 / 2 equals -3.5, and the floor is -4 because floor always rounds down toward negative infinity. The third example shows that when either operand is a float, the result is a float, but the value is still floored.
How Floor Division Handles Negative Numbers
The key distinction between floor division and truncation becomes visible with negative operands. Truncation (as seen in C's integer division or Python's int(-3.5)) rounds toward zero, giving -3. Floor division rounds toward negative infinity, giving -4.
print(-7 // 2) # -4 print(int(-7 / 2)) # -3
This behavior is intentional and consistent with the mathematical definition of floor. It also ensures that the relationship between // and % holds for all operands, as explained later.
Floor Division vs True Division
Python has two division operators: / always returns a float, while // returns an integer when both operands are integers, and a float when at least one operand is a float. True division computes the exact quotient; floor division computes the floor of that quotient.
print(7 / 2) # 3.5 print(7 // 2) # 3 print(-7 / 2) # -3.5 print(-7 // 2) # -4
Use / when you need the precise fractional result. Use // when you need an integer result and are willing to accept rounding down, such as when computing indices, counts, or steps.
The Relationship Between // and %
Floor division and the modulo operator % are mathematically linked. For any two numbers a and b where b != 0, the following identity holds:
a = (a // b) * b + (a % b)
This identity works because % returns the remainder with the same sign as the divisor, which is a consequence of floor division. For example:
a, b = -7, 2 print(a // b) # -4 print(a % b) # 1 print((a // b) * b + (a % b)) # -7
Here -4 * 2 + 1 = -7. This consistency is useful when you need to distribute a value into chunks while preserving the total.
Using floordiv with Floats
When at least one operand is a float, // returns a float, but the value is still the floor of the division. This can surprise developers who expect an integer type.
print(7.0 // 2) # 3.0 print(7 // 2.0) # 3.0 print(-7.0 // 2) # -4.0
If you need an integer result, wrap the expression with int():
result = int(7.0 // 2) # 3
Be aware that int() truncates toward zero, but since // already floors, the conversion is safe and preserves the intended value.
Common Pitfalls and Misconceptions
A frequent mistake is assuming // truncates toward zero. This leads to off-by-one errors when dealing with negative indices or coordinates. Another pitfall is mixing // with % without remembering that the sign of the remainder follows the divisor, not the dividend.
# Misleading if you expect truncation print(-7 // 2) # -4, not -3 # Remainder sign follows divisor print(-7 % 2) # 1, not -1 print(7 % -2) # -1
When porting code from languages like C or Java, check whether integer division truncates or floors. Python's // is explicitly floor division, so porting requires adjusting negative-number handling.
Performance and Runtime Considerations
For integer operands, // is typically faster than calling int(a / b) because it avoids creating an intermediate float and the associated rounding. In tight loops that perform millions of divisions, this difference can matter.
# Faster for integer division result = a // b # Slower: creates a float, then truncates result = int(a / b)
However, the performance gain is rarely the primary reason to choose //. Correctness and clarity are more important. If you need floor division, use // directly; if you need truncation, use int(a / b) or math.trunc(). Don't micro-optimize unless profiling shows it is a bottleneck.
Compatibility Notes
Python 3 changed the behavior of / to always return a float, while // remains floor division. In Python 2, / performed floor division for integers, which caused confusion. If you maintain legacy code, verify that // is used where floor division is intended, and that / is not relied upon for integer truncation.
For code that must run in both Python 2 and 3, // is the only portable way to get floor division. True division requires from __future__ import division in Python 2. Modern code should target Python 3 and use // explicitly when floor division is required.
Using floordiv in Real-World Scenarios
A common use case is pagination: given a list length and page size, you compute the number of pages. Floor division gives the correct count when the last page is partial.
total_items = 23 page_size = 10 pages = (total_items + page_size - 1) // page_size # 3
The formula (total + size - 1) // size rounds up the division result, which is a frequent pattern. Another example is converting seconds to minutes: seconds // 60 gives whole minutes, and seconds % 60 gives the remainder.
These patterns rely on the fact that // floors toward negative infinity, which keeps the math consistent even when values are negative, such as when computing time offsets or array indices.
Edge Cases and Type Behavior
Division by zero raises ZeroDivisionError for both // and /. Mixed-type operands follow the same coercion rules as other arithmetic: if either operand is a float, the result is a float. Decimal and Fraction objects also support //, but the result type depends on the implementation.
from decimal import Decimal print(Decimal(7) // Decimal(2)) # Decimal('3') from fractions import Fraction print(Fraction(7, 2) // 1) # Fraction(3, 1)
For Fraction, // returns the floor as a Fraction. For Decimal, it returns a Decimal with the integer value. These behaviors are consistent with the floor concept but may surprise users expecting a plain integer.
When working with large integers, // is exact and does not lose precision, unlike floating-point division. This makes it suitable for arbitrary-precision arithmetic in applications like cryptography or financial calculations where exact integer results are required.