Data conversion in Python, can be done implicitly (implicit data conversion) and explicitly (explicit data conversion) for primitive and non-primitive data structures.
Python Implicit Data Conversion
Implicit data conversion or coercion is something that will happen automatically in python during compilation or run time. It is handled by Python directly without losing any information.
We have the following program:
From this example, in order to calculate the sum of an integer and a float, Python have converted the integer A to a float implicitly and then store the result into a new variable C. Python create the this new variable as a float implicitly.
In this example we have not used any function to instruct Python to change the data type.
Python Explicit Data Conversion
Explicit Data Conversion also know as type casting, is opposite from Python implicit Data Conversion. In Explicit Data Conversion, we have to use function to instruct Python to do certain kind of data conversion.
Float() – Convert an object into a float
Int() – Convert an object into an integer
Str() – Convert an object into a string
tuple () – Convert a list into a tuple
list() – Convert a tuple into a list
Following table illustrated the result of using the Float, int and Str function.
|Input Data Type|
We have firstly created one list – European_Sales_list and one tuple – American_Sales_List.. Then we use the tuple function to convert the European_Sales_List into a tuple and use the list function to convert the American_Sales_List tuple to a list.
Following is the result.
Primitive Data Structure vs Non-Primitive data structures
Primitive Data Structure
Non-Primitive Data Structure
- Data Dictionary