Python Tutorial 12: Data conversion in Python

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.

For Example:

We have the following program:

Implicit data conversion in Python Implicit data conversion in Python - Result

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.

For Example

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
FloatIntegerString
5.05"5.0"
FunctionFloat()5.05.05.0
Integer()555
String()"5.0""5""5.0"

Following example demonstrated conversion between list and tuple:Conversion between List and tuple in Python

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.

Conversion between List and tuple in Python - ResultWe can see that the tuple function have converted the European_Sales_list  into a tuple and the list function have converted the American_Sales_List tuple to a list.

Primitive Data Structure vs Non-Primitive data structures

Primitive Data Structure

  • Integer
  • Float
  • String
  • Boolean

Non-Primitive Data Structure

  • List
  • Set
  • Tuple
  • Data Dictionary

Leave a Comment