Implicit Type Conversion
Python automatically converts types when it's safe to do so. This only happens when there's no risk of losing data.
# Python automatically converts int to float when mixed
result = 5 + 2.0 # int + float = float
print(result) # 7.0
print(type(result)) #
# Another example
x = True + 5 # bool + int = int (True == 1)
print(x) # 6
Explicit Type Conversion – The Big 5
Use these built-in functions to explicitly convert types: int(), float(), str(), bool(), list().
# int() - convert to integer
print(int(3.9)) # 3 (truncates, does NOT round)
print(int("42")) # 42
print(int(True)) # 1
print(int(False)) # 0
# float() - convert to float
print(float(5)) # 5.0
print(float("3.14")) # 3.14
# str() - convert to string
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
# bool() - convert to boolean
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("hello")) # True
Converting Collections
Python can convert between list, tuple, set, and dict (with some restrictions).
my_list = [1, 2, 3, 2, 1]
print(tuple(my_list)) # (1, 2, 3, 2, 1) - ordered, immutable
print(set(my_list)) # {1, 2, 3} - unique values only
print(list(set(my_list))) # back to list, but unordered
# String to list of characters
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
Conversion Errors – When Conversion Fails
Not all conversions are valid. Always handle potential ValueError when converting user input.
# This will raise ValueError
try:
x = int("hello") # Cannot convert "hello" to int
except ValueError as e:
print(f"Error: {e}")
# Safe conversion pattern
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
print(safe_int("123")) # 123
print(safe_int("abc")) # 0 (default)
Always wrap user input conversions in try/except to handle invalid input gracefully.