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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.