Skip to content

Python Datatype Casting

Data type casting, also known as type conversion, is a fundamental concept in Python that allows you to change the data type of a variable or value. This process is crucial when working with different data types and ensures the compatibility of variables in various operations. In this comprehensive guide, weโ€™ll explore the basics of data type casting in Python, including the built-in functions used for conversion and best practices.

Understanding Data Types in Python

Before we dive into the details of data type casting, letโ€™s take a moment to understand the different data types in Python. Python is a dynamically typed language, which means that the interpreter automatically assigns a data type to a variable based on the value it holds. For example, if you assign the value 55 to a variable, the interpreter will assign the integer data type to that variable. Similarly, if you assign the value 5.05.0 to a variable, the interpreter will assign the float data type to that variable.

Python supports the following data types:

Data TypeDescription
intintInteger
floatfloatFloating-point number
strstrString
boolboolBoolean
listlistList
tupletupleTuple
dictdictDictionary
setsetSet
frozensetfrozensetFrozen set
bytesbytesBytes
bytearraybytearrayByte array
complexcomplexComplex number
rangerangeRange
NoneTypeNoneTypeNone

Python Data Type Casting (Implicit Type Conversion)

Python automatically converts one data type to another when it encounters an operation that requires the two data types to be compatible. For example, if you add an integer and a float, Python will convert the integer to a float before performing the addition operation. This process is known as implicit type conversion or implicit data type casting.

The following example demonstrates how Python implicitly converts an integer to a float when performing an addition operation:

casting.py
# implicit type conversion
x = 5
y = 5.0
z = x + y
print(z)
casting.py
# implicit type conversion
x = 5
y = 5.0
z = x + y
print(z)

Output:

command
C:\Users\Your Name> python casting.py
10.0
command
C:\Users\Your Name> python casting.py
10.0

In the above example, we have added an integer and a float. Since the two data types are not compatible, Python implicitly converts the integer to a float before performing the addition operation. The result of the addition operation is then assigned to the variable zz. The value of zz is then printed to the console.

Python Data Type Casting (Explicit Type Conversion)

Python also allows you to explicitly convert one data type to another using built-in functions. This process is known as explicit type conversion or explicit data type casting. The following table lists the built-in functions used for explicit type conversion:

FunctionDescription
int()int()Converts a value to an integer
float()float()Converts a value to a float
str()str()Converts a value to a string
bool()bool()Converts a value to a boolean
list()list()Converts a value to a list
tuple()tuple()Converts a value to a tuple
dict()dict()Converts a value to a dictionary
set()set()Converts a value to a set
frozenset()frozenset()Converts a value to a frozen set
bytes()bytes()Converts a value to bytes
bytearray()bytearray()Converts a value to a byte array
complex()complex()Converts a value to a complex number
range()range()Converts a value to a range
NoneNoneConverts a value to None

Integer Conversion

int()int() Function

The int()int() function converts a value to an integer. The following example demonstrates how to use the int()int() function in Python:

casting.py
# int() function
x = 5.0
y = int(x)
print(y)
print(type(y))
casting.py
# int() function
x = 5.0
y = int(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
5
<class 'int'>
command
C:\Users\Your Name> python casting.py
5
<class 'int'>

In the above example, we have used the int()int() function to convert a float to an integer. The int()int() function takes a single argument and returns an integer. The result of the int()int() function is then assigned to the variable yy. The value of yy is then printed to the console.

Float Conversion

float()float() Function

The float()float() function converts a value to a float. The following example demonstrates how to use the float()float() function in Python:

casting.py
# float() function
x = 5
y = float(x)
print(y)
print(type(y))
casting.py
# float() function
x = 5
y = float(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
5.0
<class 'float'>
command
C:\Users\Your Name> python casting.py
5.0
<class 'float'>

In the above example, we have used the float()float() function to convert an integer to a float. The float()float() function takes a single argument and returns a float. The result of the float()float() function is then assigned to the variable yy. The value of yy is then printed to the console.

String Conversion

str()str() Function

The str()str() function converts a value to a string. The following example demonstrates how to use the str()str() function in Python:

casting.py
# str() function
x = 5
y = str(x)
print(y)
print(type(y))
casting.py
# str() function
x = 5
y = str(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
5
<class 'str'>
command
C:\Users\Your Name> python casting.py
5
<class 'str'>

In the above example, we have used the str()str() function to convert an integer to a string. The str()str() function takes a single argument and returns a string. The result of the str()str() function is then assigned to the variable yy. The value of yy is then printed to the console.

Boolean Conversion

bool()bool() Function

The bool()bool() function converts a value to a boolean. The following example demonstrates how to use the bool()bool() function in Python:

casting.py
# bool() function
x = 5
y = bool(x)
print(y)
print(type(y))
casting.py
# bool() function
x = 5
y = bool(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
True
<class 'bool'>
command
C:\Users\Your Name> python casting.py
True
<class 'bool'>

In the above example, we have used the bool()bool() function to convert an integer to a boolean. The bool()bool() function takes a single argument and returns a boolean. The result of the bool()bool() function is then assigned to the variable yy. The value of yy is then printed to the console.

List Conversion

list()list() Function

The list()list() function converts a value to a list. The following example demonstrates how to use the list()list() function in Python:

casting.py
# list() function
x = "Hello"
y = list(x)
print(y)
print(type(y))
casting.py
# list() function
x = "Hello"
y = list(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
['H', 'e', 'l', 'l', 'o']
<class 'list'>
command
C:\Users\Your Name> python casting.py
['H', 'e', 'l', 'l', 'o']
<class 'list'>

In the above example, we have used the list()list() function to convert a string to a list. The list()list() function takes a single argument and returns a list. The result of the list()list() function is then assigned to the variable yy. The value of yy is then printed to the console.

Tuple Conversion

tuple()tuple() Function

The tuple()tuple() function converts a value to a tuple. The following example demonstrates how to use the tuple()tuple() function in Python:

casting.py
# tuple() function
x = "Hello"
y = tuple(x)
print(y)
print(type(y))
casting.py
# tuple() function
x = "Hello"
y = tuple(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
('H', 'e', 'l', 'l', 'o')
<class 'tuple'>
command
C:\Users\Your Name> python casting.py
('H', 'e', 'l', 'l', 'o')
<class 'tuple'>

In the above example, we have used the tuple()tuple() function to convert a string to a tuple. The tuple()tuple() function takes a single argument and returns a tuple. The result of the tuple()tuple() function is then assigned to the variable yy. The value of yy is then printed to the console.

Dictionary Conversion

dict()dict() Function

The dict()dict() function converts a value to a dictionary. The following example demonstrates how to use the dict()dict() function in Python:

casting.py
# dict() function
x = (("name", "John"), ("age", 36)) 
y = dict(x)
print(y)
print(type(y))
casting.py
# dict() function
x = (("name", "John"), ("age", 36)) 
y = dict(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
{'name': 'John', 'age': 36}
<class 'dict'>
command
C:\Users\Your Name> python casting.py
{'name': 'John', 'age': 36}
<class 'dict'>

In the above example, we have used the dict()dict() function to convert a tuple to a dictionary. The dict()dict() function takes a single argument and returns a dictionary. The result of the dict()dict() function is then assigned to the variable yy. The value of yy is then printed to the console.

Set Conversion

set()set() Function

The set()set() function converts a value to a set. The following example demonstrates how to use the set()set() function in Python:

casting.py
# set() function
x = "Hello"
y = set(x)
print(y)
print(type(y))
casting.py
# set() function
x = "Hello"
y = set(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
{'e', 'H', 'l', 'o'}
<class 'set'>
command
C:\Users\Your Name> python casting.py
{'e', 'H', 'l', 'o'}
<class 'set'>

In the above example, we have used the set()set() function to convert a string to a set. The set()set() function takes a single argument and returns a set. The result of the set()set() function is then assigned to the variable yy. The value of yy is then printed to the console.

List to Tuple Conversion

tuple()tuple() Function

The tuple()tuple() function converts a list to a tuple. The following example demonstrates how to use the tuple()tuple() function in Python:

casting.py
# tuple() function
x = ["apple", "banana", "cherry"]
y = tuple(x)
print(y)
print(type(y))
casting.py
# tuple() function
x = ["apple", "banana", "cherry"]
y = tuple(x)
print(y)
print(type(y))

Output:

command
C:\Users\Your Name> python casting.py
('apple', 'banana', 'cherry')
<class 'tuple'>
command
C:\Users\Your Name> python casting.py
('apple', 'banana', 'cherry')
<class 'tuple'>

In the above example, we have used the tuple()tuple() function to convert a list to a tuple. The tuple()tuple() function takes a single argument and returns a tuple. The result of the tuple()tuple() function is then assigned to the variable yy. The value of yy is then printed to the console.

Conclusion

Data type casting is a crucial skill in Python programming, enabling you to handle diverse data types and ensure the compatibility of variables in different operations. Whether itโ€™s processing user input, performing mathematical operations, or working with lists, understanding when and how to use type casting is essential for writing robust and efficient code.

As you continue to explore Python, practice using explicit type casting in various scenarios, and be mindful of potential errors and data loss. For more insights and practical examples, check out our tutorials on Python Central Hub!

Was this page helpful?

Let us know how we did