Python Type Casting: Convert Between Data Types
Learn Python type casting with clear examples: convert between int, float, str, bool, and collections. Covers implicit vs explicit casting and common pitfalls.
Type casting (also called type conversion) is the process of converting a value from one data type into another. Python supports this through a set of built-in constructor functions — int(), float(), str(), bool(), list(), tuple(), set(), and more. Knowing when and how to cast is essential for writing correct, flexible Python programs.
This chapter covers:
- The difference between implicit and explicit casting
- All the major built-in casting functions with working examples
- Numeric base conversions (
hex,oct,bin, and back) - Collection type conversions (
list,tuple,set) - Boolean truthy/falsy rules and their casting gotchas
- Common errors (
TypeError,ValueError) and how to avoid them
Implicit vs Explicit Casting
Python distinguishes between two kinds of type conversion.
Implicit Casting
Implicit casting happens automatically when Python needs to reconcile two compatible types in an expression. No function call is required — Python promotes the "narrower" type to avoid data loss.
The most common case is mixing integers and floats in arithmetic. Python always converts the integer to a float so the result captures the decimal part:
Python does not implicitly convert between unrelated types such as strings and numbers. Attempting "10" + 5 raises a TypeError. For those cases you need explicit casting.
Explicit Casting
Explicit casting means calling a constructor function to convert a value yourself:
The rest of this chapter covers every important explicit-casting function in detail.
Numeric Casting: int(), float(), complex()
int() — Convert to Integer
int() accepts integers, floats, booleans, and numeric strings. When converting a float, it truncates (drops the decimal part) rather than rounding:
# float → int (truncates, does NOT round)
print(int(10.9)) # 10
print(int(-10.9)) # -10
# string → int
print(int("42")) # 42
# bool → int
print(int(True)) # 1
print(int(False)) # 0Notice that int(-10.9) returns -10, not -11. Python truncates toward zero, not toward negative infinity (that would be math.floor()).
float() — Convert to Float
float() accepts integers, booleans, and numeric strings (including "inf" and "nan"):
print(float(10)) # 10.0
print(float("3.14")) # 3.14
print(float(True)) # 1.0
print(float("inf")) # infcomplex() — Convert to Complex Number
complex() builds a complex number from real and imaginary parts, or from a string:
print(complex(3, 4)) # (3+4j)
print(complex("3+4j")) # (3+4j)String Casting: str()
str() converts almost any Python object to its string representation. This is useful for concatenation and when building output:
age = 30
message = "I am " + str(age) + " years old."
print(message) # I am 30 years old.
print(str(3.14)) # '3.14'
print(str(True)) # 'True'
print(str(None)) # 'None'For formatting numbers inside strings, see the Python f-strings chapter for a more ergonomic approach.
Boolean Casting: bool() and Truthy/Falsy Values
bool() converts any value to True or False using Python's truthy/falsy rules. Memorizing which values are falsy is important because conditions in if statements and while loops rely on the same rules implicitly.
Falsy values — these all evaluate to False:
print(bool(0)) # False — zero integer
print(bool(0.0)) # False — zero float
print(bool("")) # False — empty string
print(bool([])) # False — empty list
print(bool(None)) # False — NoneTruthy values — everything else evaluates to True:
print(bool(1)) # True
print(bool(-1)) # True — any non-zero number
print(bool("a")) # True
print(bool([0])) # True — a list with one elementCommon gotcha: Casting a string to bool always returns True unless the string is empty — even bool("False") is True. To check whether a string represents a falsy boolean, you must compare it explicitly:
# This is WRONG — bool("False") is True!
user_input = "False"
print(bool(user_input)) # True (non-empty string)
# Correct approach: compare the string
print(user_input.lower() == "true") # FalseNumeric Base Conversions
Parsing Integers in Other Bases with int()
int() accepts an optional second argument specifying the base of the source string. This lets you parse binary, octal, and hexadecimal literals:
print(int("1010", 2)) # 10 — binary string
print(int("17", 8)) # 15 — octal string
print(int("ff", 16)) # 255 — hexadecimal string
# Pass 0 to auto-detect Python prefix notation
print(int("0b1010", 0)) # 10
print(int("0o17", 0)) # 15
print(int("0xFF", 0)) # 255Converting Integers to Base Strings
Python has three built-in functions that format an integer as a base-prefixed string:
print(bin(10)) # '0b1010'
print(oct(8)) # '0o10'
print(hex(255)) # '0xff'These return strings, not integers. If you need the string without the prefix, use slicing: bin(10)[2:] gives '1010'.
Collection Type Conversions
You can convert between list, tuple, and set using their constructor functions. Converting to set removes duplicates and loses order:
# list → tuple
coords = [10, 20, 30]
print(tuple(coords)) # (10, 20, 30)
# tuple → list
point = (4, 5, 6)
mutable = list(point)
mutable.append(7)
print(mutable) # [4, 5, 6, 7]
# list → set (removes duplicates)
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(unique) # {1, 2, 3}Converting a string to a list splits it into individual characters:
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']All Numeric and String Conversions: Quick Reference
The examples below show the full range of numeric and string casting in one place:
Python casting numeric
# Converting an integer to a floating-point number
x = 10
y = float(x)
print(y)
# Converting a floating-point number to an integer
x = 10.5
y = int(x)
print(y)
# Converting a string to an integer
x = "10"
y = int(x)
print(y)
# Converting a string to a floating-point number
x = "10.5"
y = float(x)
print(y)
# Converting an integer to a string
x = 10
y = str(x)
print(y)
# Converting a floating-point number to a string
x = 10.5
y = str(x)
print(y)
# Converting a number to a boolean
x = 0
y = bool(x)
print(y)
x = 10
y = bool(x)
print(y)Common Errors
TypeError
A TypeError is raised when you pass a type that the function cannot convert at all — for example, passing a list to int():
Python casting unsupported type to int
Output:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'ValueError
A ValueError is raised when the type is right (e.g., a string) but the value cannot be converted — for example, a word passed to float():
Python casting string to float
Output:
ValueError: could not convert string to float: 'hello'Loss of Precision When Casting Float to Int
Converting a float to an int silently truncates the decimal part. There is no warning — and for negative numbers, the behavior may be surprising:
Python casting float to int
Output:
10If you need rounding, use round() before casting, or use math.floor() / math.ceil() to control direction explicitly.
Safe Casting with try/except
When your program receives data from user input, files, or external APIs, you cannot know in advance whether a value will cast successfully. Use a try/except block to handle failures without crashing:
Python safe casting with try/except
Output:
Conversion failed: invalid literal for int() with base 10: 'hello'
10This pattern is especially useful when processing form fields or CSV rows where any column might contain unexpected data.