How To Convert Data Types in Python 3?
Type Conversion is also known as typecasting, is an important feature in Python that allows developers to convert a variable of one type into another. In Python 3, type conversion can be done both explicitly (manual conversion) and implicitly (automatic conversion by Python).
Table of Content
This article will explore how to Convert Data Types in Python 3 and explain Python’s built-in functions for converting data types.
Types of Data Type Conversion
1) Implicit Type Conversion
In Python, implicit conversion happens automatically during operations when the interpreter can safely transform one data type into another without losing information.
# Implicit Conversion
x = 5 # Integer
y = 2.0 # Float
# Adding integer and float results in float
result = x + y
print(result)
print(type(result))
Output
7.0 <class 'float'>
- Here, Python converts the integer x into a float to perform the addition, ensuring that the result (7.0) is a float.
2) Explicit Type Conversion
Explicit conversion, or typecasting requires the developer to manually convert a variable from one data type to another using Python's built-in functions. This is especially useful when implicit conversion isn’t possible or when precision is necessary.
a = "42"
b = int(a)
print(type(b))
Output
<class 'int'>
- In this case, the string
"42"
is explicitly converted to an integer using theint()
function.
Common Built-In Functions for Type Conversion
Python offers a range of built-in functions for converting data types. Below are the most commonly used functions along with their examples:
Function | Description | Example |
---|---|---|
int() | Converts to an integer | int("42") -> 42 |
float() | Converts to a floating-point number | float("3.14") -> 3.14 |
str() | Converts to a string | str(42) -> "42" |
bool() | Converts to a boolean | bool(1) -> True |
list() | Converts to a list | list("abc") -> ['a', 'b', 'c'] |
tuple() | Converts to a tuple | tuple([1, 2, 3]) -> (1, 2, 3) |
set() | Converts to a set | set([1, 2, 2]) -> {1, 2} |
dict() | Converts to a dictionary (from iterable of key-value pairs) | dict([(1, 'a'), (2, 'b')]) -> {1: 'a', 2: 'b'} |
Examples of Data Type Conversion
Here are examples of converting common data types:
String to Integer or Float
User inputs are typically strings, so we often need to convert them to numerical types for calculations. so converting it to an integer or float is common. Example: int("42") or float("3.14").
# String to Integer
x = "25"
a = int(x)
print(type(a))
# String to Float
x = "25"
y = float(x)
print(type(y))
Output
<class 'int'> <class 'float'>
Integer or Float to String:
When combining numbers with text, we need to convert numbers to strings. Converting an integer to a string is often needed for tasks such as concatenating numbers with text.
# Integer to String
a = 42
b = str(a)
print(b)
# Float to String
x = 3.14159
b = str(x)
print(b)
Output
42 3.14159
List to Tuple or Set:
Converting between collections is useful for different operations like removing duplicates (with sets) or ensuring immutability (with tuples).
# List to Tuple
a = [1, 2, 3]
b = tuple(a)
print(b)
# List to Set
x = set(a)
print(x)
Output
(1, 2, 3) {1, 2, 3}
Tuple or Set to List:
Converting it to a list can help when you need an ordered or indexable structure. It helps to preserves the original order of the elements since tuples are ordered.
a = (10, 20, 30, 40)
b = {3, 1, 4, 2, 2}
# Convert tuple and set to lists
x = list(a)
y = list(b)
# Print results
print(x)
print(y)
Output
[10, 20, 30, 40] [1, 2, 3, 4]
Dictionary from Key-Value Pairs:
Using the dict() function, you can create a dictionary from an iterable of key-value pairs. We can create dictionaries from a list of tuples or other iterable structures.
x = [("a", 1), ("b", 2), ("c", 3)]
y = dict(x)
print(y)
Output
{'a': 1, 'b': 2, 'c': 3}
Boolean Conversion
We can convert any value to a boolean. In Python, 0, None, and empty sequences are considered False, and all other values are True.
# Convert to Boolean
print(bool(0))
print(bool(42))
print(bool(""))
print(bool("Hello"))
Output
False True False True