Type casting is simply the process of converting an object from one data type to another. Type casting is very important in Python because it ensures different data types can interact correctly during mathematical operations or string formatting.
Types of Type Casting
There are two categories of type casting in python, these are:
- Implicit Type Conversion: Python automatically converts one data type to another without user intervention.
- Explicit Type Conversion: The user manually converts the data type using built-in functions.
Implicit Type Conversion
Implicit conversion occurs when Python converts a value from a data type with fewer possibilities to one with broader possibilities. For example, when adding an integer to a float, 12 + 14.5, the result is expected to be 26.5. Python sees that 12 is an integer, and integers can only represent whole numbers, while floats can represent both whole numbers and decimal numbers.
Since every integer can also be represented as a float, Python automatically converts 12 to 12.0 before performing the addition. In this sense, an integer is a data type with fewer possibilities than a float, because a float can represent all integer values, but an integer cannot represent all possible float values.
A simple code example to illustrate this:
To make the conversion even more obvious:
This demonstrates that although one operand is an integer, the result is a float because Python automatically converts the integer to a float before performing the addition.
Explicit Type Conversion
Explicit type conversion is performed using built-in constructor functions. We use explicit type casting to validate data to ensure we control the type in certain processes. Lets see some of these in action
The int() Function
The int() function is used to convert a float or certain strings into an integer. It just takes the the whole number part and removes the decimals.
The float() Function
The float() function converts an integer or a compatible string into a floating-point number.
The str() Function
The str() function converts almost any data type into its string representation. This is essential for concatenating numbers with text.
The bool() Function
The bool() function is used to converts a value into a Boolean (True or False). Python uses "Truth Value Testing" to determine the result:
- False: Returned for numerical zeros (0, 0.0, 0j), empty containers ("", [], (), {}), None, and False itself.
- True: Returned for all other values.
The complex() Function
The complex() function is used to create a complex number. It can take either one or two arguments.
Casting Collections (Iterables)
Python allows for conversion between different collection types using their respective constructors. This is often used to change the properties of a data set (e.g., making a list unique by converting it to a set).
The list() Function
The list() function converts an iterable (like a string, tuple, or set) into a list.
The tuple() Function
The tuple() function converts an iterable into an immutable tuple.
The set() Function
The set() function converts an iterable into a set. This process automatically removes any duplicate elements.
The dict() Function
The dict() function creates a dictionary. To cast into a dictionary, the input must be a sequence of "pairs" (usually a list of tuples).
Summary
- Definition: Type casting is the manual or automatic transformation of a data type.
- Implicit Conversion: Python automatically promotes types (e.g.,
inttofloat) to avoid data loss. - Explicit Conversion: Performed using functions like
int(),float(),str(), andbool(). - Truncation: The
int()function removes decimals without rounding. - Compatibility: Strings must contain only numeric characters to be cast into integers or floats.
