Python Type Conversion
Type conversion is the process of converting a value from one data type to another. Python provides several built-in functions for converting values between different data types.
For example, a string containing a number can be converted into an
integer using int(), while an integer can be converted
into a floating-point number using float().
Types of Type Conversion
Python type conversion can be classified into two main types:
| Type | Description |
|---|---|
| Implicit Type Conversion | Python automatically converts a value from one compatible data type to another. |
| Explicit Type Conversion | The programmer manually converts a value using a built-in conversion function. |
1. Implicit Type Conversion
In implicit type conversion, Python automatically converts one compatible data type into another without requiring the programmer to specify the conversion.
This commonly occurs when integer and floating-point values are used together in an arithmetic expression.
a = 10
b = 2.5
result = a + b
print(result)
print(type(result))
12.5 <class 'float'>
Here, a is an integer and b is a float.
Python automatically converts the integer to a floating-point value
for the calculation.
Another Example of Implicit Conversion
x = 5
y = 2.0
z = x * y
print(z)
print(type(z))
10.0 <class 'float'>
2. Explicit Type Conversion
In explicit type conversion, the programmer manually converts a value from one data type to another by using a conversion function.
Common conversion functions include
int(), float(), str(),
bool(), list(), tuple()
and set().
x = "25"
number = int(x)
print(number)
print(type(number))
25 <class 'int'>
3. Converting to Integer Using int()
The int() function converts a compatible value into
an integer.
String to Integer
value = "100"
number = int(value)
print(number)
print(type(number))
100 <class 'int'>
Float to Integer
When a floating-point value is converted to an integer, the fractional part is removed. The value is not rounded to the nearest integer.
value = 25.75
number = int(value)
print(number)
25
Negative Float to Integer
value = -25.75
print(int(value))
-25
The int() conversion truncates the fractional part
toward zero.
4. Converting to Float Using float()
The float() function converts a compatible value into
a floating-point number.
Integer to Float
number = 25
value = float(number)
print(value)
print(type(value))
25.0 <class 'float'>
String to Float
value = "99.50"
number = float(value)
print(number)
print(type(number))
99.5 <class 'float'>
5. Converting to String Using str()
The str() function converts a value into a string.
This is useful when numeric values need to be combined with text.
number = 100
text = str(number)
print(text)
print(type(text))
100 <class 'str'>
Using str() with Text
age = 20
message = "My age is " + str(age)
print(message)
My age is 20
6. Converting to Boolean Using bool()
The bool() function converts a value into either
True or False.
print(bool(1))
print(bool(0))
print(bool(10))
print(bool(-5))
True False True True
Boolean Conversion of Strings
A non-empty string is considered true, while an empty string is considered false.
print(bool("Python"))
print(bool("False"))
print(bool(""))
True True False
bool("False") returns True because
"False" is a non-empty string. Python does not interpret
the text as the Boolean value False in this conversion.
7. Converting List to Tuple
The tuple() function can convert a list into a tuple.
numbers = [10, 20, 30]
result = tuple(numbers)
print(result)
print(type(result))
(10, 20, 30) <class 'tuple'>
8. Converting Tuple to List
The list() function can convert a tuple into a list.
values = (10, 20, 30)
result = list(values)
print(result)
print(type(result))
[10, 20, 30] <class 'list'>
9. Converting List to Set
The set() function converts an iterable into a set.
Duplicate values are automatically removed.
numbers = [10, 20, 10, 30, 20]
result = set(numbers)
print(result)
{10, 20, 30}
A set is unordered, so the displayed order of its elements should not be relied upon.
10. Converting String to List
Using list() on a string creates a list containing
its individual characters.
text = "Python"
result = list(text)
print(result)
['P', 'y', 't', 'h', 'o', 'n']
11. Converting String to Tuple
text = "ABC"
result = tuple(text)
print(result)
('A', 'B', 'C')
12. Converting String to Set
text = "hello"
result = set(text)
print(result)
A set stores only unique elements and does not guarantee a particular display order.
13. Type Conversion of User Input
The input() function returns the entered value as a
string. Therefore, conversion is normally required when numerical
calculations are performed.
age = input("Enter your age: ")
print(type(age))
Enter your age: 20 <class 'str'>
To receive the age as an integer, use int().
age = int(input("Enter your age: "))
print(age)
print(type(age))
Enter your age: 20 20 <class 'int'>
14. Multiple Input with Type Conversion
The map() function can be used with a conversion
function to convert multiple input values.
a, b, c = map(int, input("Enter three numbers: ").split())
print("Sum =", a + b + c)
Enter three numbers: 10 20 30 Sum = 60
15. Type Conversion in Arithmetic Operations
Type conversion is frequently used when a program receives numeric values as strings.
a = "10"
b = "20"
result = int(a) + int(b)
print("Sum =", result)
Sum = 30
Without conversion, the + operator would concatenate
the two strings instead of performing numeric addition.
a = "10"
b = "20"
print(a + b)
1020
16. Invalid Type Conversion
A conversion may fail if the value is not compatible with the requested data type.
value = "Hello"
number = int(value)
print(number)
The above program raises a ValueError because
"Hello" cannot be converted into an integer.
17. Checking the Type After Conversion
The type() function can be used to check the data type
before and after conversion.
value = "50"
number = int(value)
print("Before:", type(value))
print("After:", type(number))
Before: <class 'str'> After: <class 'int'>
Common Type Conversion Functions
| Function | Conversion | Example |
|---|---|---|
int() |
Convert to integer | int("25") |
float() |
Convert to float | float("25.5") |
str() |
Convert to string | str(25) |
bool() |
Convert to Boolean | bool(1) |
list() |
Convert to list | list("ABC") |
tuple() |
Convert to tuple | tuple([1, 2]) |
set() |
Convert to set | set([1, 2, 2]) |
Implicit vs Explicit Type Conversion
| Feature | Implicit Conversion | Explicit Conversion |
|---|---|---|
| Performed by | Python automatically | Programmer |
| Function required | Usually no | Yes |
| Example | 10 + 2.5 |
int("10") |
| Purpose | Compatible calculations | Convert data as required by the program |
Important Points
- Type conversion changes a value from one data type to another.
- Implicit conversion is performed automatically by Python.
- Explicit conversion is performed by the programmer.
int()converts compatible values to integers.float()converts compatible values to floating-point numbers.str()converts a value into a string.bool()converts a value intoTrueorFalse.list(),tuple()andset()can convert compatible iterables.input()returns user input as a string.- Invalid conversions can raise exceptions such as
ValueError. - The
type()function can be used to verify the resulting data type.
int(), float(), str(),
bool(), list(), tuple()
and set().