In Python, type conversion (also known as type casting) is the process of converting an object of one data type to another data type. This is useful when you need to perform operations that require specific data types, or when you want to ensure that your data is in a specific format.
There are two types of type conversion in Python: Implicit Type Conversion, Explicit Type Conversion.
Implicit Type Conversion
Implicit type conversion occurs automatically when Python converts one data type to another without user intervention. This typically happens when operations are performed between different data types.
# Implicit conversion of int to float num_int = 10 num_float = 5.5 result = num_int + num_float print(result) # Output: 15.5
In this example, the integer num_int
is implicitly converted to a float to perform addition with num_float
.
Explicit Type Conversion
Explicit type conversion, also known as type casting, involves converting a data type into another explicitly using predefined functions like int()
, float()
, str()
, etc.
# Explicit conversion from float to int num_float = 3.7 num_int = int(num_float) print(num_int) # Output: 3
Here, the float value num_float
is explicitly converted to an integer using the int()
function.
Built-in Type Conversion Functions
Python provides several built-in functions for explicit type conversion:
int()
Converts a string or float to an integer.
x = "10" y = int(x) # converts string to int
float()
Converts a string or integer to a float.
x = "10.5" y = float(x) # converts string to float
str()
Converts any object to a string.
x = 10 y = str(x) # converts int to string
bool()
Converts any object to a boolean value (True
or False
).
x = 0 y = bool(x) # converts int to bool (False)
list()
Converts an iterable object to a list.
x = (1, 2, 3) y = list(x) # converts tuple to list
tuple()
Converts an iterable object to a tuple.
x = [1, 2, 3] y = tuple(x) # converts list to tuple
dict()
Converts a sequence of key-value pairs to a dictionary.
x = [("a", 1), ("b", 2)] y = dict(x) # converts list of tuples to dict
set()
Converts an iterable object to a set.
x = [1, 2, 2, 3] y = set(x) # converts list to set (removes duplicates)
Best Practices
- Use explicit type conversion whenever possible: This makes your code more explicit and easier to understand.
- Avoid implicit type conversion: It can lead to unexpected behavior and make your code harder to debug.
- Be mindful of performance: Type conversion can be costly in terms of performance, so use it judiciously.