Topic 34 of 64
Explicit Type Casting
Overview
Python is strongly typed so implicit conversions are rare. Explicit type casting with int(), float(), str(), list(), bool() etc. is required whenever you need to convert between types — common in data processing and API handling.
Syntax
python
# Type conversion functions
int("42") # 42
int(3.9) # 3 (truncates, not rounds!)
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
list("abc") # ['a', 'b', 'c']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 1, 2, 3]) # {1, 2, 3}Common Pitfalls
- int('3.14') raises ValueError — you must first convert to float: int(float('3.14')).
- int(3.9) truncates toward zero, not rounds — use round() for rounding behavior.
- Interview tip: Type casting does NOT change the original object — Python creates a new object of the target type.
Real-World Example
Parse and validate incoming JSON API data with proper type casting
example
python
def parse_user_data(raw: dict) -> dict:
return {
"id": int(raw.get("id", 0)),
"name": str(raw.get("name", "")).strip(),
"age": int(raw.get("age", 0)),
"active": bool(raw.get("active", False)),
"scores": list(raw.get("scores", [])),
}
data = {"id": "42", "name": " Alice ", "age": "30", "active": 1}
print(parse_user_data(data))