Type Conversion in Python


The data type is the classification of data items it tells the interpreter how a user is intended to use the data. Python has various data types and a variable is automatically declared on the basis of the value that you assign to it.

Sometimes a data type is needed to be converted to another type. The process of conversion of the value of one data type to another data type is called type conversion.

In this article, we will discuss how one data is converted to another in Python along with some examples.

Types of type conversion in Python

There are two types of type conversion in Python –

  • Implicit type conversion
  • Explicit type conversion

Let’s see these in detail.

Implicit type conversion

In implicit type conversion, data is converted from one data type to another automatically without the involvement of the user. For example, When you add one integer type to a float type the result is automatically converted to in float.

You can see the example below –

a =20
print(type(a))
b= 10.5
print(type(b))
b=b+a
print(b)
print(type(b))

You can see the output in the given image –

Explicit type conversion

In explicit type conversion a user use method like int(), float(), complex() to convert data from one type to another. This type of conversion is also known as typecasting.

The given example shows how you can convert data from one type to another.

a = 2 # int type
b= 10.5 # float type
c= 5j # complex type
d= '1501' # string type
# convert int to float type
x = float(a)
# convert float to int
y = int(b)
# convert int or float to complex
z = complex(a)
# convert a string to int
num = int (d)
# Dispaly the type of x,y,z, and num
print(type(x))
print(type(y))
print(type(c))
print(type(num))

Now you can see the output in the given image –

Apart from this, you can use the following method to convert data from one data type to another.

str() – it converts an integer into a string

tuple() – convert data to tuple data type

set() – convert to Python set type

list() – convert any other data type to list type

dict() – this function converts a tuple of the order (key, value) to dictionary type

That all for now. You can try the given function on your own if you find any difficulty then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.