Document 1
Document 1
done by using the type conversion functions to directly convert one data type to
another
In the implicit type conversion, the Python interpreter automatically converts one
data type of objects to another using specified functions without any user
involvement preventing data loss.
Example
x = 10
print(type(x))
y = 10.6
print(type(y))
z=x+y
print(type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type.
The reason for the float value not being converted into an integer instead is due
to type promotion that allows performing operations by converting data into a
wider-sized data type without any loss of information. This is a simple case of
Implicit type conversion in Python.
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data type.
Example
# initializing string
s = "10010"
# initializing string
c = set(s)
print (c)
c = list(s)
print (c)
Output:
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']