In Python programming, type conversion (also known as type casting) is the process of converting one data type into another. Python supports multiple ways of converting types, making it simple yet powerful for managing data.
1. What is Type Conversion?
Type conversion in Python refers to changing data from one type to another explicitly or implicitly. For example:
- Converting a string
"10"
into an integer10
. - Converting an integer
3
into a float3.0
.
This technique is especially useful when working with data from external sources (like user input, files, or web APIs) where data type mismatches may occur.
2. Types of Type Conversion
Python offers two kinds of type conversions:
a) Implicit Type Conversion
Implicit type conversion (automatic type conversion) occurs when Python converts one data type to another automatically during operations.
x = 10 # integer
y = 2.5 # float
result = x + y # integer is implicitly converted to float
print(result) # 12.5
print(type(result)) # <class 'float'>
Python automatically converts the integer (10
) to a float (10.0
) to avoid data loss.
b) Explicit Type Conversion
Explicit type conversion involves manually converting a data type using built-in functions.
num_str = "123" # String
num_int = int(num_str) # Explicitly converting to integer
print(num_int) # 123
print(type(num_int)) # <class 'int'>
3. Common Type Conversion Functions
Python provides built-in functions for explicit type conversions:
Function | Description | Example |
---|---|---|
int() | Converts to integer | int("10") → 10 |
float() | Converts to float | float("3.14") → 3.14 |
str() | Converts to string | str(100) → "100" |
list() | Converts iterable to list | list((1, 2, 3)) → [1, 2, 3] |
tuple() | Converts iterable to tuple | tuple([1, 2]) → (1, 2) |
set() | Converts iterable to set | set([1, 1, 2]) → {1, 2} |
dict() | Converts to dictionary | dict([(1, 'one')]) → {1: 'one'} |
bool() | Converts to Boolean | bool(0) → False, bool(1) → True |
4. Examples of Type Conversions
Here are practical examples demonstrating type conversions:
a) String to Integer
age_str = "25"
age_int = int(age_str)
print(age_int, type(age_int))
b) Integer to Float
x = 5
x_float = float(x)
print(x_float, type(x_float))
c) Float to Integer (Truncation)
pi = 3.14159
pi_int = int(pi) # Removes decimal part
print(pi_int) # 3
d) String to List
name = "Alice"
name_list = list(name)
print(name_list) # ['A', 'l', 'i', 'c', 'e']
e) List to Set
numbers = [1, 2, 2, 3, 3]
unique_numbers = set(numbers)
print(unique_numbers) # {1, 2, 3}
f) Tuple to Dictionary
pairs = [("a", 1), ("b", 2)]
dict_pairs = dict(pairs)
print(dict_pairs) # {'a': 1, 'b': 2}
g) Boolean Conversion
print(bool(0)) # False
print(bool(5)) # True
print(bool("")) # False
print(bool("Python")) # True
5. Errors in Type Conversions
Type conversion can cause errors when incompatible conversions are attempted:
invalid_int = int("hello") # Raises ValueError
Common Errors:
- ValueError: Occurs when data cannot be converted logically.
- TypeError: Occurs when a non-iterable is used where an iterable is expected (e.g., converting an integer directly into a list).
Preventing errors:
- Always validate data before converting.
- Use
try-except
blocks for error handling.
try:
number = int("ten")
except ValueError:
print("Conversion failed. Invalid integer.")