Type Conversion in Python – Free Python Tutorials

In this tutorial today we will discuss the type conversion in Python. Type conversion is used when we have to convert one data type into another. For this purpose of type conversion in Python, we have a set of pre-defined functions which we can make use of. To successfully carry about these type conversions in python let’s get to know about them in details.


complex() method in Python

This is used to convert other data types to complex data type. There are 2 types:

  1. complex(a)
  2. complex(a,b)

Here when we pass only one argument then it is considered the real part. Whereas when two are passed then the second one is taken as the imaginary part. These functions are overloaded functions.


1) complex(a) :-

  • int to complex :- For converting the int value into a complex data type we just write the int value in the predefined function.
    Example: >>>complex(5)
    Output: (5+0j)

  • float to complex :- For converting the int value into a complex data type we just write the float value in the predefined function.
    Example: >>>complex(40.7)
    Output:(40.7+0j)

This line of code simply takes the float value entered and treats it like the real part of the number while the imaginary part remains zero by default.


  • Boolean to complex :- For converting the int value into a complex data type we just write the boolean True or False value in the predefined function.
    Example: >>>complex(True)
    Output:(1+0j)

The above line of code takes the boolean value ‘True’ and takes its value 1 as the real part of the number while the imaginary part remains zero by default.

Example:  >>>complex(False)
Output:(0j)

The above line of code takes the boolean value ‘False’ and takes its value 0 as the real part of the number while the imaginary part remains zero by default.


  • String to Complex :- A variable of string data type can be converted to complex data type only when the string contains numerical values with base 10. Any other format does not get converted and gives an error.
  • Now we will look at several examples of how to make use of the complex() function.

Example: >>>complex(“30”)
Output:(30+0j)

In this line of code, we take the number ’30’ input in the str data type which is then is converted and used as the real part of the complex number.

Example:>>>complex(“six”)
Output:ValueError

In the above line, we take the input as a str type but it is not a numerical input and hence yields a value error on executing.

Example:>>>complex(0b1110)
Output:ValueError

In the above line, we take the input as a str type but it is not a numerical input with base 10 as it is a binary input and hence yields a value error on executing.


2) complex(a,b)

It is very similar to the complex function with one argument.

  • int to complex :- To convert the int value into a complex data type we just write the two int values separated by a comma in the predefined function.
    Example: >>>complex(5, 10)
    Output:(5+10j)

This line of code simply takes the first int value entered and treats it like the real part of the number while the second number is an imaginary part by default.


  • float to complex :- To convert the int value into a complex data type we just write the float values separated by a comma in the predefined function.
    Example: >>>complex(12, 40.7)
    Output:(12+40.7j)

This line of code simply takes the first int value entered and treats it like the real part of the number while the second number with floating point is an imaginary part.


  • Boolean to complex :- For converting the int value into a complex data type we just write the boolean True or False values in the predefined function.
    Example: >>>complex(True, False)
    Output:(1+0j)

The above line of code takes the first boolean value entered i.e. ‘True’ with a value of 1 and treats it like the real part of the number while the second value is ‘False’ i.e. zero is an imaginary part.


  • String to complex :- Two consecutive variable of string data type cannot be converted to complex data type and gives an error.
    Example:>>>complex(“30”, “13”)
    Output :TypeError: complex() can’t take second arg if first is a string

As we can see from the above example that when both the values are of str type then it cannot be converted. This means that while converting from the string we can only give the first value as a string data type.


bool() conversion in Python

While converting to boolean form our output can only be True, False or an Error. It is possible to use with almost every fundamental data type.

  • int to bool() :- In the bool function if we enter any numerical value that is non-zero then the output it will yield is always True. Whereas if we enter 0 then the output is False.
    Example: >>>bool(1)
    Output:True

As we know that any value that is not zero will result in True with the bool function. Here in our example above the value is 1 and so it will be True.


  • Float to bool() :- For converting from float data type if we enter any numerical value that is non-zero then the output it will yield is always True. Whereas if we enter 0.0 then the output is False.
    Example: >>>bool(0.0)
    Output :False

    Example : >>>bool(0.005)
    Output:True

Any value that is just greater than or lesser than zero will result in True with the bool function. Here in our example above the value is 0.005 and hence it will be True.


  • Complex to bool() :- For converting the complex data type value into a boolean data type if we enter any value in the real and imaginary part that is non zero then the output will be true, otherwise false.
    Example: >>>bool(5+7j)
    Output: True

The complex number entered i.e. 5+7j is non zero and hence results in True.


  • String to bool() :- While converting from string to complex if the string entered is empty i.e. (‘’) then the output is False otherwise true.
    Example: >>>bool(‘’)
    Output:False

    Example: >>>bool(‘meow’)
    Output:True

Note: However if we leave a blank space between the opening and closing commas then output would be true as a blank space is also a character.


str() conversion in Python

It is really very convenient to convert any type into a string. Literally, any type can be converted without any error.

  • int to str() :-
    Example: >>>str(100)
    Output:’100’

In the example, the input entered in str() is of integer data type i.e. it is a whole number and gets converted to str data type.


  • Float to str() :-
    Example: >>>str(100.98)
    Output:’100.98’

In the code above, the input entered in str() function is in the format of a floating point number and gets converted to str data type.


  • Complex to str() :-
    Example:>>>str(5+10j)
    Output:’(5+10j)’

In the example, the input entered is in the format of a complex number and gets converted to str data type.


  • String to bool() :-
    Example:>>>str(True)
    Output:‘True’

In the above example, we see that ‘True’ is used with the str() function and is straightaway converted to boolean data type.


Immutable Vs Fundamental Data Types

Immutable:

  • When we can’t change a data type after creating it then we call it immutable. All the fundamental data types are immutable. e.g.- int, float, etc.
  • As we know that everything in Python is an object, hence whenever we change the value of an immutable then a new object is created.
    Example:
    >>>a= 1
    >>>b= 1
  • Here, when an object has been created already for 1 then all the references of this will be shared in future. This improves performance and memory utilization by object re-usability.
  • This can be very helpful when a large number of variables share the same value.

Example:

>>>s1= “Mew”

>>>s2= “Mew”

>>>s3= “Mew”

>>>s4= “Mew”

id(s1)

32343560

id(s2)

32343560

Here when we check for the address of the internal object then all the references point to the same object having value ‘Mew’. Therefore we get the same output.

  • The letdown of this functionality is that if one reference changes the object then the value of all the references will change.
  • To overcome this drawback when one reference changes the object then a new object is created.
  • This would mean that the original object remains unaltered by the implementation of immutability.

Example:

>>>s1= “Mew”

>>>s2= “Mew”

>>>s3= “Mew”

>>>s4= “Mew”

>>>s2= “Meow”

id(s1)

32343560

id(s3)

32343560

id(s2)

87343045

Here we see that the address of s2 has changed since now its value has changed from ‘Mew’ to ‘Meow’ and thus now points to a different object.

  • Instead of checking address by address we can also simply check if the variables point to the same object by using ‘is’.

Example:

>>>a= 1

>>>b= 1

>>>a is b

Output:True

We can see the output is True i.e. both point to the same object since both a and b have the same value.

Note: This concept of object reusability is only limited from 0 to 256.


Example:

>>>a= 300

>>>b= 300

>>>a is b

Output: False

Here the numbers taken are 300 in variables a and b. Since 300 is not in the range of 0 to 265 we get False as output.

Note: Object reusability is not applicable for floating point numbers and complex numbers.


Example:

>>>a= 1.1

>>>b= 1.1

>>>a is b

Output: False

Here the numbers taken are 1.1 in variables a and b. Since 1.1 is a floating point number we get False as output.

This is all about the type conversion in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *