Ad – 728×90
🌱 Beginner

Python Type Conversion – int(), float(), str(), bool() and More

Type conversion (or type casting) is the process of converting a value from one data type to another. Python supports both implicit conversion (done automatically) and explicit conversion (done by the programmer using built-in functions). Understanding this is essential because many bugs come from using the wrong type.

⏱️ 18 min read 🎯 Beginner 📅 Updated 2026

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
# 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
▶ Output
7.0 6

Explicit Type Conversion – The Big 5

Use these built-in functions to explicitly convert types: int(), float(), str(), bool(), list().

Python
# 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
▶ Output
3 42 1 0 5.0 3.14 42 3.14 True False True False True
Ad – 336×280

Converting Collections

Python can convert between list, tuple, set, and dict (with some restrictions).

Python
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']
▶ Output
(1, 2, 3, 2, 1) {1, 2, 3} [1, 2, 3] ['h', 'e', 'l', 'l', 'o']

Conversion Errors – When Conversion Fails

Not all conversions are valid. Always handle potential ValueError when converting user input.

Python
# 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)
▶ Output
Error: invalid literal for int() with base 10: 'hello' 123 0
💡
Tip

Always wrap user input conversions in try/except to handle invalid input gracefully.