Javatpoint Logo
Javatpoint Logo

Typecasting in Python

One of the key features in Python is "Typecasting". Typecasting in Python allows programmers to convert variables or data from one data type to another. It enables smooth manipulation of data. Typecasting in Python can be very useful in dealing with large data sets where the data is present in different data types. Also, by leveraging the power of typecasting in Python, we can convert mutable datatypes into immutable ones and vice versa.

Suppose you want to store some user ids and passwords. You wouldn't like to store them in mutable data types and allow someone to change them. Here, you can typecast those mutable variables into immutable ones and secure those ids and passwords.

And most of the time, we typecast while taking inputs from the user. As we all know, in Python, all the inputs stored are in the form of strings. We typecast these inputs according to our specific requirements.

Note: Python follows certain typecasting rules. During the process of typecasting, the lower precision value is typecasted into a higher precision value to avoid losing any information.

In this tutorial, we will learn how typecasting happens in Python and explore its applications, benefits, and potential pitfalls.

Common Typecasting Techniques in Python

We come across different kinds of arithmetic operations in which multiple data types are involved, and then results are obtained accordingly.

Python offers two ways to perform typecasting. Here we will discuss both,

  1. Implicit type conversion
  2. Explicit type conversion

Let's understand them with the help of programs-

1. Implicit Type Conversion in Python

In Python, implicit typecasting is automatically performed. During the implicit type conversion, the user is not supposed to mention any specific data type during the conversion. For example, while multiplying an integer and a floating-point number, Python implicitly converts the integer value into a floating-point value to perform the multiplication.

The following program illustrates how implicit typecasting is done in Python.

Output:

a = 10 and Data type = <class 'int'>
b = 4.5 and Data type = <class 'float'>
c = 4 and Data type = <class 'int'>
d = 5.0 and Data type = <class 'float'>
The product of a and b is 45.0, Data type = <class 'float'>
The addition of c and d is 9.0, Data type = <class 'float'>

Explanation-

Let's have a glance at the explanation of this program.

  1. To check how the values get converted on performing the operations, we have initialized the values of a, b, c, and d.
  2. After this, we checked the data type of each one of them.
  3. Finally, we have performed addition on the variables a and b and multiplication on the variables c and d.
  4. On executing the above program, we can observe that in the case of the product, the final result is a float value as a was an integer value, and b was a float value. Also, in the case of an addition, the final result is a float value, as c was an integer value and d was a float value.

We can observe that the integer value is less precise than the floating value. Thus, the integer values are converted into a floating value during the implicit type conversion.

Now, it's time to move on to the next topic which is explicit type conversion.

2. Explicit Type Conversion in Python

Python allows us to explicitly typecast the data type of a variable using the in-built functions. In explicit type conversion in Python, the user is supposed to pass the value in a function to obtain the required data type.

The most commonly used functions for the explicit type conversion are as follows:

  • int(): Converts a value to an integer.
  • float(): Converts a value to a floating-point number.
  • str(): Converts a value to a string.
  • bool(): Converts a value to a Boolean (True or False).
  • list(): Converts an iterable to a list.
  • tuple(): Converts an iterable to a tuple

Let us now see how we can achieve explicit typecasting with an example. Consider the programs given below:

A. Converting a value to an integer:

Output:

a = 10.6, Data Type = <class 'float'>
a = 10, Data Type = <class 'int'>

b = 12, Data Type = <class 'str'>
b = 12, Data Type = <class 'int'>

Explanation:

In the above example, the int() function explicitly converts a float 10.6 and a string "12" to an integer.

B. Converting a value to a floating-point number:

Output:

c = 10, Data Type = <class 'int'>
c = 10.0, Data Type = <class 'float'> 
  
d = 15, Data Type = <class 'str'>
d = 15.0, Data Type = <class 'float'> 

Explanation:

In the above example, the float() function explicitly converts an integer 10 and a string "6" to an integer.

C. Converting a value to a String

Output:

a = 10, Data Type = <class 'int'>
a = '10', Data Type = <class 'str'>

b = 15.0, Data Type = <class 'float'> 
b = '15.0', Data Type = <class 'str'>

Explanation:

In the above example, the str() function explicitly converts an integer 10 and a floating-point value 15.0 to a string.

D. Converting an iterable into a List

Output:

a = (1, 2, 3, 4, 5), Data Type = <class 'tuple'>
a = [1, 2, 3, 4, 5], Data Type = <class 'list'>

b = {1, 2, 3, 4, 5}, Data Type = <class 'set'>
b = [1, 2, 3, 4, 5], Data Type = <class 'list'>

Explanation:

In the above example, the list() function explicitly converts a tuple (1, 2, 3, 4, 5) and a set {1, 2, 3, 4, 5} to a list.

Note: Similar to the above example, you can convert an iterable into a set using the set() function, into a tuple using the tuple() function, and into a string using the str() function.

Benefits of Typecasting in Python:

Till now, we have understood how typecasting can play a crucial role in data manipulation and execution of various operations in Python. The following are some benefits of typecasting:

  • Input Validation - In Python, typecasting is often used to validate the user's input. We can make sure that the data provided by the users is in the desired format. If not, we can convert the input to a desired data type.
  • Flexibility - In Python, typecasting gives flexibility to programmers to work with various data types. Programmers can easily convert data types of varibales. Because of this, Python is more suitable for a wide range of applications.
  • Mathematical Operations - Programmers can easily perform mathematical operations between different data types and obtain accurate results because of typecasting.

Pitfalls and Considerations of Typecasting in Python:

While typecasting offers several benefits, one should always be aware of potential pitfalls and considerations:

  • Data Loss - If unaware, one might lose information while typecasting, resulting in less accurate results. As we know, Python follows certain typecasting rules. One should always ensure that there is no loss of information while typecasting a high-precision value (a floating value) into a low-precision value (an integer value).
  • Impact on Performance - Typecasting takes a significant amount of time. Excessive typecasting can lead to the bad performance of the program because of unnecessary overheads.
  • Type Safety - Unwanted form of typecasting can cause unwanted behaviors in the program and can result in a program crash. One should ensure that the typecasting in done properly to get desired and accurate result.

CONCLUSION:

Typecasting is a powerful tool in Python. It provides flexibility, ease in input validation, and ease in mathematical operations to the programmers. In this tutorial, we learned what typecasting is in Python, the types of typecasting in Python, implicit and explicit type castings, and how it can be performed in Python. We then deep-dived into both types of typecasting and implemented them through examples. We have also seen the benefits and pitfalls of typecasting.

It is essential for the programmers to handle type conversions carefully to avoid losing information and maintain program's reliability and result's accuracy.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA