Table of contents
1.
Introduction
2.
Implicit Type Conversion in Python
2.1.
Example
2.2.
Python
3.
Explicit Type Conversion in Python
3.1.
Example
3.2.
Python
3.3.
Converting Integer to Float
3.4.
Python
4.
Python Type Conversion Using ord(), hex(), oct()
4.1.
ord() Function
4.2.
Python
4.3.
hex() Function
4.4.
Python
4.5.
oct() Function
4.6.
Python
5.
Python Type Conversion Using tuple(), set(), list()
5.1.
tuple() Function
5.2.
Python
5.3.
set() Function
5.4.
Python
5.5.
list() Function:
6.
Python Code to Demonstrate Type Conversion Using dict(), complex(), str()
6.1.
dict() Function
6.2.
complex() Function
6.3.
Python
6.4.
str() Function
6.5.
Python
7.
Frequently Asked Questions
7.1.
What is type conversion in Python?
7.2.
When should I use explicit type conversion?
7.3.
Can type conversion lead to data loss?
8.
Conclusion
Last Updated: Apr 23, 2024
Medium

Type Conversion in Python

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Type conversion is a fundamental concept in Python that allows you to change the data type of a value from one type to another. It is an essential skill for any Python programmer to master, as it enables you to work with different types of data in your programs. 

Type Conversion in Python

In this article, we will learn the basics of type conversion in Python, including implicit & explicit type conversion, as well as how to convert between various data types such as integers, floats, strings, tuples, lists, & dictionaries. 

Implicit Type Conversion in Python

Implicit type conversion, or automatic type conversion, happens in Python when the interpreter automatically converts one data type to another without any explicit instruction from the programmer. This feature is useful because it simplifies code and avoids errors that might arise from incompatible operations. For example, when you perform arithmetic operations between integers and floats, Python automatically converts the integer to a float to avoid loss of precision.

Example

  • Python

Python

# Adding an integer and a float
num_int = 3 # Integer value
num_float = 6.5 # Float value

# Python automatically converts integer to float for addition
result = num_int + num_float

print("Data type of num_int:", type(num_int))
print("Data type of num_float:", type(num_float))
print("Value of result:", result)
print("Data type of result:", type(result))
You can also try this code with Online Python Compiler
Run Code

Output

Data type of num_int: <class 'int'>
Data type of num_float: <class 'float'>
Value of result: 9.5
Data type of result: <class 'float'>


In this code, num_int is an integer and num_float is a float. When these are added together, Python converts num_int to a float implicitly and performs the addition, resulting in a float value in result. This conversion ensures that there is no loss of information, and the operation is performed accurately.

Explicit Type Conversion in Python

Explicit type conversion, also known as type casting, requires the programmer to explicitly change the data type of an object. This approach is necessary when you need to perform operations that are not supported by automatic conversion, or when you need precise control over how data types behave together.

Example

  • Python

Python

# Converting float to integer
num_float = 9.7 # Float value
# Explicitly converting float to integer
num_int = int(num_float)
print("Float value:", num_float)
print("Integer value after conversion:", num_int)
You can also try this code with Online Python Compiler
Run Code

Output

Float value: 9.7
Integer value after conversion: 9


In the above example, num_float is initially a float with a value of 9.7. The int() function is used to explicitly convert this float into an integer. The result is that the decimal part is truncated, and num_int becomes 9. This type of conversion is handy when you need to discard the decimal part and work with whole numbers only.

Converting Integer to Float

Converting an integer to a float in Python is a straightforward process that increases the precision of the integer value by transforming it into a floating-point number. This is particularly useful when you need more accurate results in calculations that involve division or require floating-point precision.

Example:

  • Python

Python

# Converting integer to float
num_int = 4 # Integer value
# Explicitly converting integer to float
num_float = float(num_int)
print("Integer value:", num_int)
print("Float value after conversion:", num_float)
You can also try this code with Online Python Compiler
Run Code

Output

Integer value: 4
Float value after conversion: 4.0


In this example, num_int is an integer with a value of 4. Using the float() function, we explicitly convert num_int into a float. The result is num_float which now holds the value 4.0. This conversion is essential for accurate calculations in scenarios where precision is critical, such as scientific computations and graphical representations.

Python Type Conversion Using ord(), hex(), oct()

Python provides several built-in functions that allow you to convert values between different data types and formats. Functions like ord(), hex(), and oct() are essential tools when working with character encodings and numeric representations.

ord() Function

The ord() function converts a character into its corresponding Unicode code point. This is useful in scenarios where you need the numeric representation of a specific character for encoding or processing purposes.

Example:

  • Python

Python

# Converting a character to its Unicode code point
char = 'A'
unicode_code = ord(char)
print("Character:", char)
print("Unicode code point of", char, "is", unicode_code)
You can also try this code with Online Python Compiler
Run Code

Output

Character: A
Unicode code point of A is 65

hex() Function

The hex() function converts an integer to a hexadecimal string. This is often used in contexts where hexadecimal numbers are needed, such as in color codes, memory addresses, or data that involves low-level programming.

Example:

  • Python

Python

# Converting an integer to hexadecimal
num = 255
hex_value = hex(num)
print("Integer:", num)
print("Hexadecimal value of", num, "is", hex_value)
You can also try this code with Online Python Compiler
Run Code

Output

Integer: 255
Hexadecimal value of 255 is 0xff

oct() Function

Similarly, the oct() function converts an integer to an octal string. This might be used in systems where octal notation is preferable or required.

Example:

  • Python

Python

# Converting an integer to octal
num = 64
octal_value = oct(num)
print("Integer:", num)
print("Octal value of", num, "is", octal_value)
You can also try this code with Online Python Compiler
Run Code

Output

Integer: 64
Octal value of 64 is 0o100


These functions provide straightforward ways to manipulate and convert data types in Python, enhancing the versatility & accuracy of your programming tasks.

Python Type Conversion Using tuple(), set(), list()

Python allows for easy conversion between different collection types—specifically, tuples, sets, and lists. Each type has unique characteristics and is useful in different programming scenarios. Converting between these types can be crucial for data manipulation and meeting the requirements of various functions or methods.

tuple() Function

The tuple() function is used to convert an iterable (like a list or a set) into a tuple. Tuples are immutable, which means they cannot be changed after they are created. This is beneficial when you need a constant set of values that should not be modified.

Example:

  • Python

Python

# Converting a list to a tuple
list_values = [1, 2, 3, 4]
tuple_values = tuple(list_values)
print("List:", list_values)
print("Tuple:", tuple_values)
You can also try this code with Online Python Compiler
Run Code

Output

List: [1, 2, 3, 4]
Tuple: (1, 2, 3, 4)

set() Function

The set() function converts an iterable into a set, which is an unordered collection of unique elements. This function is incredibly useful for removing duplicates from a list and for performing common set operations like unions, intersections, and differences.

Example:

  • Python

Python

# Converting a list to a set to remove duplicates
list_values = [1, 1, 2, 2, 3, 4]
set_values = set(list_values)
print("List with duplicates:", list_values)
print("Set with unique elements:", set_values)
You can also try this code with Online Python Compiler
Run Code

Output

List with duplicates: [1, 1, 2, 2, 3, 4]
Set with unique elements: {1, 2, 3, 4}

list() Function:

The list() function converts an iterable into a list. Lists are mutable and can contain duplicates, making them ideal for data that needs to be changed or updated.

Example:

# Converting a tuple to a list

tuple_values = (5, 6, 7, 8)

list_values = list(tuple_values)

print("Tuple:", tuple_values)

print("List:", list_values)

These conversion functions enhance flexibility in how data is handled and stored, allowing for easier manipulation and adaptation to specific programming needs.

Python Code to Demonstrate Type Conversion Using dict(), complex(), str()

Python's versatility in type conversion extends to more complex data types. Functions like dict(), complex(), and str() enable you to work with dictionaries, complex numbers, and strings respectively, allowing for a broad range of data manipulations and conversions.

dict() Function

The dict() function is used to convert collections into a dictionary, which is a key-value store that is highly efficient for lookup operations. This function can be especially useful when you need to create dictionaries from lists of tuples or other sequences that represent key-value pairs.

Example:

# Converting list of tuples into a dictionary
list_of_tuples = [('key1', 'value1'), ('key2', 'value2')]
dictionary = dict(list_of_tuples)
print("Dictionary:", dictionary)

complex() Function

The complex() function is used to create a complex number from real and imaginary parts. Complex numbers are important in fields such as engineering and scientific computing, where they are used to perform calculations involving square roots of negative numbers.

Example:

  • Python

Python

# Creating a complex number

real_part = 3

imaginary_part = 5

complex_number = complex(real_part, imaginary_part)

print("Complex number:", complex_number)
You can also try this code with Online Python Compiler
Run Code

Output

Complex number: (3+5j)

str() Function

The str() function converts an object into its string representation. This is often used for displaying information, logging, or for operations that require string manipulation.

Example:

  • Python

Python

# Converting an integer to a string
integer_value = 10
string_value = str(integer_value)
print("Integer:", integer_value)
print("String representation:", string_value)
You can also try this code with Online Python Compiler
Run Code

Output

Integer: 10
String representation: 10


These functions offer powerful options for converting data types in Python, making your code more flexible and adaptable to various needs.

Frequently Asked Questions

What is type conversion in Python?

Type conversion in Python refers to changing the data type of an object to another, enabling compatibility and proper execution of operations in code. This can be either implicit (automatic) or explicit (manual).

When should I use explicit type conversion?

Explicit type conversion should be used when Python does not automatically convert data types, or when precise control over the conversion process is necessary, such as when truncating floats to integers or when handling complex data structures.

Can type conversion lead to data loss?

Yes, certain type conversions can lead to data loss, such as converting a float to an integer where the decimal part is removed, or converting a set to a list where duplicate values were previously eliminated.

Conclusion

In this article, we have learned about the essential concepts and techniques of type conversion in Python. We explored how implicit and explicit conversions differ and when to use them. We also discussed various Python functions like ord(), hex(), oct(), tuple(), set(), list(), dict(), complex(), and str() to effectively manage and convert data types. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass