In Python, type conversion refers to the process of converting one data type to another, its Called typecasting. This is an essential concept because sometimes we need to change the type of a value to perform specific operations. For example, converting a string to an integer or a float to an integer. Python makes type conversion straightforward with built-in functions, allowing us to convert between various types easily.
Typecasting is the process of converting the value of a single data type (such as an integer [int], float, or double) into another data type.
1. Implicit Type Conversion (Type Coercion)
Python automatically converts one data type to another when necessary. This is known as implicit type conversion or type coercion. It happens automatically when the operation requires mixing different data types, and Python decides on the best way to handle the conversion.
Example:
# Implicit conversion x = 5 # Integer y = 2.5 # Float # When an integer and a float are added, Python converts the integer to float result = x + y print(result) # Output: 7.5 print(type(result)) # Output: <class 'float'>
In the example above, Python automatically converts the integer x
to a float before performing the addition because the other operand (y
) is a float. The result is stored as a float.
2. Explicit Type Conversion (Type Casting)
Explicit type conversion occurs when we manually convert one data type to another using built-in functions. This is often called type casting. Python provides several functions for explicitly converting between types.
Common Type Conversion Functions
int()
: Converts a value to an integer (removes decimals, if any).float()
: Converts a value to a floating-point number.str()
: Converts a value to a string.bool()
: Converts a value to a Boolean (True
orFalse
).list()
: Converts a sequence (e.g., tuple, string) into a list.tuple()
: Converts a sequence (e.g., list, string) into a tuple.set()
: Converts a sequence into a set.
Examples of Type Conversion
Converting to Integer (int()
):
# Convert float to integer x = 3.7 y = int(x) # Converts to 3 (decimal part is discarded) print(y) # Output: 3 print(type(y)) # Output: <class 'int'>
Converting to Float (float()
):
# Convert integer to float x = 10 y = float(x) # Converts to 10.0 print(y) # Output: 10.0 print(type(y)) # Output: <class 'float'>
Converting to String (str()
):
# Convert integer to string x = 42 y = str(x) # Converts to "42" print(y) # Output: "42" print(type(y)) # Output: <class 'str'>
Converting to Boolean (bool()
):
# Convert various values to boolean x = 1 y = bool(x) # Non-zero numbers are considered True print(y) # Output: True z = 0 w = bool(z) # Zero is considered False print(w) # Output: False
Converting to List (list()
):
# Convert string to list x = "Hello" y = list(x) # Converts each character in the string to a list element print(y) # Output: ['H', 'e', 'l', 'l', 'o']
Converting to Tuple (tuple()
):
# Convert list to tuple x = [1, 2, 3] y = tuple(x) # Converts the list into a tuple print(y) # Output: (1, 2, 3)
3. Type Conversion Between Collections
You can convert between various collection types in Python. For example, you can convert a string to a list, a tuple to a set, or a list to a set. This is useful when you need to manipulate the data differently.
Example: Converting a List to a Set:
# Convert list to set my_list = [1, 2, 2, 3, 4, 4] my_set = set(my_list) # Removes duplicates print(my_set) # Output: {1, 2, 3, 4}
In this case, the list has duplicates, but when converted to a set, the duplicates are automatically removed since sets cannot contain duplicate values.
4. Handling Invalid Conversions
Sometimes, you may attempt to convert a value to a type that is incompatible, such as trying to convert a string that doesn’t represent a number to an integer. In such cases, Python will raise an error.
Example:
# Invalid conversion: string to integer x = "Hello" y = int(x) # Raises ValueError
To handle such situations gracefully, you can use a try-except
block to catch the error and avoid program crashes.
Example of Handling Errors:
try: x = "Hello" y = int(x) # This will raise an error except ValueError: print("Cannot convert string to integer!")
Output:
Cannot convert string to integer!
5. Conversions Between Similar Data Types
When working with values that are very similar, such as converting a float to an integer, Python will either truncate the value or round it depending on the method used.
Example:
# Using int() truncates the decimal part x = 9.99 y = int(x) # Converts to 9 (decimals are discarded) print(y) # Output: 9 # Using round() rounds the value z = round(x) # Rounds to the nearest integer print(z) # Output: 10