Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python int Usage: Conversion, Arithmetic, and Pitfalls

Understand the int() constructor, base conversion, arithmetic behavior, large integers, and common pitfalls for reliable Python code.

~5 min readPython
#int() constructor#type conversion#integer arithmetic#floor division
Illustration of Python integer conversion showing a string being parsed into a numeric integer object with a gear icon representing arithmetic operations.

Python int usage goes beyond simple integer literals. The int() constructor, base handling, and arithmetic semantics shape how integers behave in real code. Misunderstanding these details leads to subtle bugs, especially when converting user input, parsing configuration files, or performing division in data pipelines.

The int() Constructor and Its Base Parameter

The most common way to create an integer from another type is int(x). When x is a float, the value is truncated toward zero, not rounded. This is a frequent source of surprise:

python
>>> int(3.99) 3 >>> int(-2.7) -2

If you need rounding, use round() before converting, or keep the float and round at the end. Truncation is intentional but often not what a developer expects when parsing measurements.

The constructor also accepts a string and an optional base. The base must be 0 or between 2 and 36, inclusive. If no base is given, the string is parsed as decimal, but leading whitespace and a sign are allowed:

python
>>> int(' -42 ') -42

When a base is supplied, the string must be a valid literal in that base. For example, int('ff', 16) returns 255. Bases 2, 8, and 16 also accept their normal prefixes, so int('0xff', 16) and int('0b1010', 2) are valid as well:

python
>>> int('ff', 16) 255 >>> int('0xff', 16) 255 >>> int('0b1010', 2) 10

If you pass 0 as the base, Python infers the base from the prefix: 0x for hexadecimal, 0o for octal, 0b for binary, and decimal when there is no prefix. This mode is useful when parsing prefixed strings from external systems.

Integer Literals and Numeric Separators

Python supports integer literals in decimal, binary, octal, and hexadecimal. The prefix determines the base:

BasePrefixExampleDecimal value
Binary0b0b101010
Octal0o0o1210
Hexadecimal0x0x0A10

Since Python 3.6, underscores can separate digits for readability. They are ignored by the interpreter but make large constants easier to read:

python
population = 8_000_000_000 mask = 0b_1111_0000

Underscores are allowed between digits and immediately after the base prefix, but not at the beginning or end. They help when defining bit masks or large configuration values.

Integer Arithmetic and Division Semantics

Integers support the standard arithmetic operators +, -, *, /, //, %, and **. Division, however, is where many developers stumble. The / operator always returns a float, even when both operands are integers and the result is exact:

python
>>> 10 / 2 5.0

If you need an integer result, use the floor division operator //. It floors the result, so for positive numbers it is the same as truncation, but for negative numbers it rounds toward negative infinity:

python
>>> 7 // 2 3 >>> -7 // 2 -4

The modulo operator % pairs with // to satisfy the identity a == (a // b) * b + a % b for nonzero b. With negative operands, this differs from C-style truncating division: -7 // 2 is -4, and -7 % 2 is 1 because the remainder follows the sign of the divisor in Python. This is important when implementing cyclic indexing or time calculations where negative values must wrap consistently.

For exact integer division with truncation toward zero, int(a / b) works for small values, but the float conversion can lose precision or raise OverflowError for very large integers. If you need truncation for arbitrary-size integers, use abs(a) // abs(b) and restore the sign yourself. When you need floor semantics and the remainder, divmod(a, b) is clearer than separate // and % calls and computes both in one operation:

python
>>> divmod(-7, 2) (-4, 1)

Handling Large Integers and Memory Considerations

Python integers are arbitrary precision. They grow as large as memory allows, which is a double-edged sword. On the one hand, you never encounter overflow in the C sense. On the other hand, operations on very large integers become slower and consume more memory. A number with millions of digits will cause noticeable latency and memory pressure.

Internally, CPython stores integers as arrays of 30-bit digits on common builds. Memory usage therefore scales with the number of digits, not a fixed size. For typical application data, this is irrelevant. But when processing cryptographic operations, large factorial computations, or bit shifts of enormous values, be aware that each operation allocates a new integer object. There is no in-place mutation.

If you are doing many arithmetic operations on large integers, consider whether you can reduce the magnitude early. For example, when computing a product modulo a number, apply the modulo after each multiplication to keep intermediate values small. This avoids allocating huge temporary integers.

Common Conversion Pitfalls and Type Errors

The int() constructor raises ValueError for malformed strings and TypeError for unsupported types. A common mistake is passing a string with a decimal point or a currency symbol:

python
>>> int('3.14') ValueError: invalid literal for int() with base 10: '3.14'

To parse a decimal string, first convert to float and then to int, but be aware that this introduces floating-point rounding. For exact decimal parsing from user input, use the decimal.Decimal type and then convert to int if necessary.

Another pitfall is converting a bytes object directly. int(b'42') works, but int(b'4.2') raises ValueError. If you receive bytes from a network socket, decode to a string first and handle the encoding explicitly.

When converting a boolean, int(True) returns 1 and int(False) returns 0. This is often used in legacy code to convert flags, but it can hide type errors. Prefer explicit checks like 1 if condition else 0 for readability.

Performance Considerations for Frequent int Operations

If your code calls int() on the same value repeatedly, caching the result avoids re-parsing the string. For example, when processing a list of numeric strings in a loop, convert once and store the integer in a new list rather than converting on each access.

Micro-optimizations such as choosing // over int(a / b) can matter only when floor semantics are acceptable; for negative operands the two are not equivalent. The bigger win is avoiding unnecessary conversions altogether. If a value is already an int, int(value) is unnecessary; it adds overhead and can hide mistakes if the value was actually something else.

For large integer arithmetic, allocation cost can dominate. Reusing variables does not help because integers are immutable; each operation creates a new object. x += 1 also creates a new integer, but x = x * 2 in a loop that runs a million times will create progressively larger integers, so allocation and calculation costs grow. If you only need the final result modulo some number, apply the modulo inside the loop to keep the values small.

Finally, recent CPython releases include a configurable limit on the number of digits allowed in integer-string conversions; the default is commonly 4300. If your application legitimately parses very large numbers, you may need to raise the limit with sys.set_int_max_str_digits(). It is a security measure against denial-of-service via extremely long numeric strings, so only raise it when necessary and validate input length separately.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.