Data type conversion in Python refers to the process of changing the data type of a value from
one type to another. This can occur either implicitly (automatically by Python) or explicitly
(manually by the programmer). [1]
Implicit Type Conversion (Type Coercion):
Python automatically converts one data type to another during operations involving mixed types
to prevent data loss. This typically occurs when combining a smaller data type with a larger one,
such as an integer with a float, where the integer is implicitly converted to a float to perform the
operation. [1]
num_int = 10
num_float = 5.5
result = num_int + num_float
print(result)
print(type(result))
In this example, num_int (integer) is implicitly converted to a float before addition with
num_float, resulting in a float value for result.
Explicit Type Conversion (Type Casting):
Programmers manually convert data types using built-in functions. This is often necessary when
a specific data type is required for an operation or when converting between incompatible types
that Python cannot implicitly handle.
Common explicit conversion functions include:
● int(): Converts a value to an integer.
str_num = "123"
int_num = int(str_num)
print(int_num)
print(type(int_num))
● float(): Converts a value to a floating-point number.
int_val = 10
float_val = float(int_val)
print(float_val)
print(type(float_val))
● str(): Converts a value to a string.
num = 456
str_val = str(num)
print(str_val)
print(type(str_val))
list(),
tuple(), set(), dict(): Used to convert between collection types, provided the data structure allows
for such conversion.
Considerations:
Explicit type conversion can lead to data loss if the target data type cannot fully represent the
original value (e.g., converting a float with decimal places to an integer). Python raises a
TypeError if an explicit conversion is attempted on incompatible types (e.g., converting a
non-numeric string to an integer).
AI responses may include mistakes.
[1] [Link]