Python Type Conversions

Learn about type conversions in Python, including implicit and explicit conversions, and common conversion functions.

Last updated: 2024-12-12

Type conversion in Python refers to the process of converting one data type into another. This is a crucial concept for handling different types of data efficiently.


Types of Type Conversion

There are two main types of type conversions in Python:

  1. Implicit Type Conversion
  2. Explicit Type Conversion (Type Casting)

1. Implicit Type Conversion

Python automatically converts one data type to another when needed, without user intervention.

Key Features:

  • Automatic type conversion.
  • No data loss in the process.

Example 1: Integer to Float

x = 5   # Integer
y = 2.5 # Float
result = x + y   # x is implicitly converted to float
print(result)    # Output: 7.5
print(type(result))   # Output: <class 'float'>

Example 2: Boolean to Integer

a = True  # Boolean (True is treated as 1)
b = False # Boolean (False is treated as 0)
result = a + b
print(result)    # Output: 1
print(type(result))  # Output: <class 'int'>

Example 3: String Concatenation

name = "John"
age = 25
# Implicit type conversion happens during string formatting
message = f"My name is {name} and I am {age} years old."
print(message)

2. Explicit Type Conversion (Type Casting)

Explicit type conversion occurs when the programmer manually converts one data type into another using built-in functions.

Common Type Conversion Functions:

  • int() – Converts to an integer.
  • float() – Converts to a float.
  • str() – Converts to a string.
  • bool() – Converts to a boolean.
  • list() – Converts to a list.
  • tuple() – Converts to a tuple.
  • set() – Converts to a set.
  • dict() – Converts to a dictionary.

Example 1: Float to Integer

x = 9.8
converted_x = int(x)  # Drops the decimal part
print(converted_x)    # Output: 9

Example 2: String to Integer

s = "123"
converted_s = int(s)
print(converted_s)    # Output: 123
print(type(converted_s))  # Output: <class 'int'>

Example 3: Integer to String

num = 100
converted_num = str(num)
print(converted_num)   # Output: '100'
print(type(converted_num))  # Output: <class 'str'>

Example 4: List to Tuple

my_list = [1, 2, 3, 4]
converted_tuple = tuple(my_list)
print(converted_tuple)  # Output: (1, 2, 3, 4)

Advanced Type Conversions

Using eval()

The eval() function can execute a string as Python code.

expr = "3 + 5"
result = eval(expr)
print(result)   # Output: 8

Using ord() and chr()

These functions convert between characters and their Unicode codes.

print(ord('A'))  # Output: 65
print(chr(65))   # Output: 'A'

Using complex()

Creates complex numbers.

real = 3
imaginary = 4
c = complex(real, imaginary)
print(c)   # Output: (3+4j)

Common Type Conversion Errors

  1. ValueError: Raised when conversion fails due to invalid input.

    s = "abc"
    int(s)  # This will raise ValueError
    
  2. TypeError: Raised when conversion between incompatible types is attempted.

    int_val = 5
    str_val = "Hello"
    result = int_val + str_val  # This will raise TypeError
    

Best Practices for Type Conversion

  • Check Data Types: Use type() to check data types before converting.
  • Handle Exceptions: Use try-except blocks to avoid runtime errors.
  • Avoid Implicit Assumptions: Be aware of implicit type conversions in operations.

Conclusion

Type conversion in Python is a versatile tool for handling different data types efficiently. Understanding both implicit and explicit conversions allows developers to write cleaner, more robust, and error-free code.

More Information

  1. Python Type Conversion