Type conversion
suggest changePython is a strongly typed language: it does not automatically convert values between incompatible types (for example, attempting "Price: " + 42 raises a TypeError). Type conversion—converting a value from one data type to another—can be either implicit (promoted automatically by the interpreter) or explicit (performed by invoking constructor functions).
Implicit Type Conversion
Python automatically promotes numeric types during arithmetic operations to prevent precision loss:
x = 10 # int
y = 2.5 # float
result = x + y
print(result) # 12.5
print(type(result)) # <class 'float'>
Booleans are a subclass of integers (True == 1, False == 0), so they are also promoted in arithmetic:
print(True + 5) # 6
print(False * 42) # 0
Explicit Conversion Functions
Explicit conversion is performed using built-in type constructors:
1. Integer Conversion (int)
int() converts floats by truncating towards zero, and converts strings into integers:
# Truncation of float
print(int(9.99)) # 9
print(int(-4.7)) # -4
# String to int
print(int("123")) # 123
# String with custom radix / base
print(int("1010", 2)) # 10 (binary)
print(int("ff", 16)) # 255 (hexadecimal)
print(int("77", 8)) # 63 (octal)
Attempting to parse an invalid string raises a ValueError:
try:
int("hello")
except ValueError as e:
print(f"Conversion error: {e}")
2. Floating-Point Conversion (float)
print(float(42)) # 42.0
print(float("3.14159")) # 3.14159
print(float("1e-4")) # 0.0001 (scientific notation)
print(float("inf")) # inf (infinity)
3. String Conversion (str and repr)
str()returns a human-readable, user-facing representation.repr()returns an unambiguous representation often matching valid Python code.
import datetime
now = datetime.datetime(2026, 10, 17, 12, 0, 0)
print(str(now)) # 2026-10-17 12:00:00
print(repr(now)) # datetime.datetime(2026, 10, 17, 12, 0)
4. Boolean Conversion (bool)
Any value can be converted to a boolean according to its truthiness:
# Falsy values evaluate to False:
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
# Truthy values evaluate to True:
print(bool(42)) # True
print(bool("hello")) # True
print(bool([1, 2])) # True
Collection Conversions
You can convert between iterable collection types:
# List, Tuple, and Set conversions
numbers_list = [1, 2, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple) # (1, 2, 2, 3, 4)
# Set removes duplicate items:
unique_set = set(numbers_list)
print(unique_set) # {1, 2, 3, 4}
# Constructing dictionaries from pairs:
pairs = [("id", 101), ("name", "Alice"), ("active", True)]
user_dict = dict(pairs)
print(user_dict) # {'id': 101, 'name': 'Alice', 'active': True}
# Converting parallel lists to a dictionary:
keys = ["a", "b", "c"]
values = [10, 20, 30]
mapped = dict(zip(keys, values))
print(mapped) # {'a': 10, 'b': 20, 'c': 30}
Implementing Custom Conversions
Custom classes can define special dunder methods to support built-in type conversions:
class Temperature:
def __init__(self, celsius: float):
self.celsius = celsius
def __int__(self) -> int:
return int(self.celsius)
def __float__(self) -> float:
return float(self.celsius)
def __bool__(self) -> bool:
return self.celsius > 0.0
def __str__(self) -> str:
return f"{self.celsius}°C"
t = Temperature(21.7)
print(str(t)) # 21.7°C
print(int(t)) # 21
print(float(t)) # 21.7
print(bool(t)) # True