8.3 Explicit Type Conversion (Type Casting)
Manually requesting a type conversion by calling the target type as a function, why it's called 'casting', and the common real-world use cases that require it.
Definition
What Is It?
Manually requesting a conversion by calling the target type as a function — int(x), str(x), float(x), and so on.
Why Is It Called “Casting”?
Borrowed terminology from languages like C/Java, where a value is explicitly “cast” to a different type.
>>> int("42")
42
Why Explicit Conversion Is Needed
Whenever a conversion isn’t automatic (str to int/float, list to set, and so on) or could lose information (float to int), Python requires an explicit opt-in — this makes the possibility of data loss or an invalid conversion visible in the code, rather than silent. See 8.9 Type Conversion Errors for what happens when the value can’t actually be converted.
Common Use Cases
- Converting
input()text to a number for arithmetic - Converting a parsed JSON/CSV string field to its real type
- Converting a list to a set for deduplication or fast membership testing
- Converting any object to
strfor logging, printing, or display
Quick Interview Answer
“Explicit conversion — type casting — is calling the target type directly as a function, like
int(x)orstr(x), to manually request a conversion Python won’t perform on its own. It’s required for any conversion that isn’t a safe, automatic numeric promotion, or that could lose information, likefloattoint— Python deliberately makes those visible in the code rather than doing them silently.”
Common Mistakes
- Reaching for a manual string-parsing workaround instead of the appropriate built-in cast —
int(x),float(x), and friends already handle the common cases correctly. - Casting a value without first confirming it’s convertible, and letting an unhandled exception crash the program — see 8.10 Safe Type Conversion.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form