8.2 Implicit Type Conversion
How Python automatically promotes int to float in mixed arithmetic, why bool participates as a subclass of int, and why implicit conversion never bridges fundamentally incompatible types like str and int.
Implicit conversion happens automatically; explicit conversion is requested directly.
Definition
What Is It?
Python automatically converting one type to another in certain mixed-type expressions, without being asked.
Why Is It Used?
For conversions that are always safe and lossless, requiring the programmer to convert manually every time would just be repetitive noise.
Automatic Conversion Rules
The main rule: when int and float are mixed in an arithmetic expression, the int is automatically promoted to float, since float can represent every int value (within precision limits) but not vice versa.
Examples
>>> 1 + 2.5 # int automatically promoted to float
3.5
>>> type(1 + 2.5)
<class 'float'>
>>> True + 1 # bool is a subclass of int -- promotes to int
2
Advantages
- No boilerplate conversion code needed for safe, common cases
- Prevents accidental precision loss (never silently truncates
intfrom afloat)
Limitations
- Only works for a small set of built-in, well-defined promotions (mainly numeric)
- Does not apply between fundamentally incompatible types (
strandintdo not implicitly combine)
>>> "5" + 3 # NOT automatic -- str and int don't implicitly combine
Traceback (most recent call last):
TypeError: can only concatenate str (not "int") to str
Quick Interview Answer
“Implicit conversion is Python automatically promoting one type to another in a mixed-type expression, without an explicit call — the main real-world case is
intpromoting tofloatin mixed arithmetic, sincefloatcan safely represent everyintvalue. It’s deliberately narrow: it only covers well-defined, lossless numeric promotions (includingbool, since it’s a subclass ofint), and it never bridges fundamentally incompatible types likestrandint—\"5\" + 3raises aTypeErrorrather than silently converting either side.”
Common Mistakes
- Expecting
"5" + 3to work the way some other dynamically typed languages implicitly coerce strings and numbers — Python raises aTypeErrorinstead. - Assuming implicit conversion happens for any “compatible-looking” types — it’s limited to the specific numeric promotions Python defines, not a general rule.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form