How To Convert Data Types in Python 3?
Last Updated :
16 Dec, 2024
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).
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.
Python
# Implicit Conversion
x = 5 # Integer
y = 2.0 # Float
# Adding integer and float results in float
result = x + y
print(result)
print(type(result))
Output7.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.
Python
a = "42"
b = int(a)
print(type(b))
- In this case, the string
"42"
is explicitly converted to an integer using the int()
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").
Python
# 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.
Python
# Integer to String
a = 42
b = str(a)
print(b)
# Float to String
x = 3.14159
b = str(x)
print(b)
List to Tuple or Set:
Converting between collections is useful for different operations like removing duplicates (with sets) or ensuring immutability (with tuples).
Python
# 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.
Python
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.
Python
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.
Python
# Convert to Boolean
print(bool(0))
print(bool(42))
print(bool(""))
print(bool("Hello"))
OutputFalse
True
False
True
Similar Reads
How to convert Float to Int in Python? In Python, you can convert a float to an integer using type conversion. This process changes the data type of a value However, such conversions may be lossy, as the decimal part is often discarded.For example:Converting 2.0 (float) to 2 (int) is safe because here, no data is lost.But converting 3.4
5 min read
Type Conversion in Python Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Python Implicit Type C
5 min read
How to Convert to Best Data Types Automatically in Pandas? Let's learn how to automatically convert columns to the best data types in a Pandas DataFrame using the convert_dtypes() method.Convert Data Type of a Pandas Series using convert_dtypes() FunctionTo convert the data type of a pandas series, simply use the following syntax: Syntax: series_name.conver
2 min read
How to Convert Bytes to String in Python ? We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'.This article covers different ways to convert bytes into strings in Pyt
2 min read
Convert String to Float in Python The goal of converting a string to a float in Python is to ensure that numeric text, such as "33.28", can be used in mathematical operations. For example, if a variable contains the value "33.28", we may want to convert it to a float to perform operations like addition or division. Let's explore dif
2 min read