How to Convert Data Types in Python - Python Tutorial | Logic Practice
Python Course / Data Types / How to Convert Data Types in Python

How to Convert Data Types in Python

BLUF: This lesson on How to Convert Data Types in Python provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: How to Convert Data Types in Python

Mastering How to Convert Data Types in Python is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

Typecasting in Python

A significant characteristic of Python is "Typecasting." In Python, typecasting facilitates the conversion of variables or data from one type to another, allowing for seamless data manipulation. This capability proves to be extremely advantageous when working with extensive data sets that contain various data types. Furthermore, by utilizing the functionality of typecasting in Python, it becomes possible to transform mutable data types into immutable ones and the other way around.

Imagine you need to save user IDs and passwords. It is not advisable to keep them in mutable data types, as this would permit alterations. In this case, you can convert those mutable variables into immutable types, thereby safeguarding the user IDs and passwords.

Frequently, we perform typecasting when receiving inputs from users. It is well-known that in Python, all user inputs are initially stored as strings. We then convert these inputs to the desired data types based on our specific needs.

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 guide, we will delve into the process of typecasting in Python, examining its uses, advantages, and possible drawbacks.

Common Typecasting Techniques in Python

We encounter various forms of arithmetic operations that involve multiple data types, leading to results generated based on those types.

Python provides two methods for typecasting. In this discussion, we will cover both of them:

  • Implicit type conversion
  • Explicit type conversion

Let's understand them with the help of programs-

1. Implicit Type Conversion in Python

In Python, automatic typecasting occurs without any intervention from the user. When implicit type conversion takes place, there is no need for the user to specify any data type for the conversion process. For instance, when an integer is multiplied by a floating-point number, Python automatically transforms the integer into a floating-point number to carry out the multiplication.

The program below demonstrates the process of implicit typecasting in Python.

Example

# Python program to demonstrate implicit type conversion
# Initializing the value of a
a = 10
print(f"a = {a} and Data type = {type(a)}")

# Initializing the value of b
b = 4.5
print(f"b = {b} and Data type = {type(b)}")

# Initializing the value of c
c = 4
print(f"c = {c} and Data type = {type(c)}")

# Initializing the value of d
d = 5.0
print(f"d = {d} and Data type = {type(d)}")

# Performing arithmetic operations between integers and float
res = a * b
print(f"The product of a and b is {res}, Data type = {type(res)}")

add = c + d
print(f"The addition of c and d is {add}, Data type = {type(add)}")

Output:

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.

  • To check how the values get converted on performing the operations, we have initialized the values of a, b, c, and d.
  • After this, we checked the data type of each one of them.
  • Finally, we have performed addition on the variables a and b and multiplication on the variables c and d.
  • 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.

It is evident that the precision of integer values is inferior to that of floating-point values. Consequently, during the process of implicit type conversion, integer values are transformed into floating-point values.

Next, we will transition to our following subject, which focuses on explicit type conversion.

2. Explicit Type Conversion in Python

Python provides the capability to explicitly convert the data type of a variable through its built-in functions. In the process of explicit type conversion in Python, the user is required to supply a value into a function in order to achieve the desired 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

Now, let’s explore how we can perform explicit typecasting through an illustrative example. Examine the programs provided below:

A. Converting a value to an integer:

Example

# Python program to demonstrate explicit type conversion

# Typecasting a floating value into an integer value explicitly
a = 10.6
print(f"a = {a}, Data Type = {type(a)}")
a = int(a)
print(f"a = {a}, Data Type = {type(a)}")

# Typecasting a string value into an integer value explicitly
b = "12"
print(f"b = {b}, Data Type = {type(b)}")
b = int(b)
print(f"b = {b}, Data Type = {type(b)}")

Output:

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 example provided, the int function is used to explicitly transform a float value of 10.6 and a string "12" into integers.

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

Example

# Python program to demonstrate explicit type conversion

# Typecasting an integer value into a floating-point number explicitly
c = 10
print(f"c = {c}, Data Type = {type(c)}")
c = float(c)
print(f"c = {c}, Data Type = {type(c)}")

# Typecasting a string into a floating-point number explicitly
d = "15"
print(f"d = {d}, Data Type = {type(d)}")
d = float(d)
print(f"d = {d}, Data Type = {type(d)}")

Output:

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 aforementioned illustration, the float function is utilized to explicitly transform the integer 10 and the string "6" into a floating-point number.

C. Converting a value to a String

Example

# Python program to demonstrate explicit type conversion

# Typecasting an integer value into a string explicitly
a = 10
print(f"a = {a}, Data Type = {type(a)}")
a = str(a)
print(f"a = '{a}', Data Type = {type(a)}")

# Typecasting a floating-point number into a string explicitly
b = 15.0
print(f"b = {b}, Data Type = {type(b)}")
b = str(b)
print(f"b = '{b}', Data Type = {type(b)}")

Output:

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 example provided, the str function is used to deliberately transform the integer 10 and the floating-point number 15.0 into their string representations.

D. Converting an iterable into a List

Example

# Python program to demonstrate explicit type conversion

# Typecasting a tuple into a list explicitly
a = (1, 2, 3, 4, 5)
print(f"a = {a}, Data Type = {type(a)}")
a = list(a)
print(f"a = {a}, Data Type = {type(a)}")

# Typecasting a set into a list explicitly
b = {1, 2, 3, 4, 5}
print(f"b = {b}, Data Type = {type(b)}")
b = list(b)
print(f"b = {b}, Data Type = {type(b)}")

Output:

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 preceding example, the list method is used to explicitly transform a tuple (1, 2, 3, 4, 5) and a set {1, 2, 3, 4, 5} into a list format.

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 serves as an essential feature within Python. It offers programmers enhanced flexibility, simplifies input validation, and streamlines mathematical computations. In this tutorial, we explored the concept of typecasting in Python, examining the various forms of typecasting available, including implicit and explicit conversions, as well as the methods to perform these conversions in Python. We then thoroughly examined both categories of typecasting, demonstrating their applications through practical examples. Additionally, we discussed the advantages and potential drawbacks associated with typecasting.

It is crucial for developers to manage type conversions with caution to prevent the loss of information and to ensure the program's reliability and the accuracy of its results.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience