Python TypeConversion

Type conversion in Python refers to converting a variable from one data type to another. Python provides two types of type conversion:

  1. Implicit Type Conversion (Automatic)
  2. Explicit Type Conversion (Type Casting)

Implicit Type Conversion (Automatic):

This occurs automatically when Python converts one data type to another without any explicit instruction from the user. Python does this to avoid data loss and errors when working with mixed types. Generally, Python will convert smaller types to larger types (e.g., int to float).


# Implicit type conversion from int to float
intNum = 20
floatNum = 15.0

# Adding int and float results in a float
result = intNum + floatNum 
print(result)          # Output: 35.0
print(type(result))    # Output: 

In the example above, Python automatically converts intNum (an integer) to a float because the result of adding an integer and a float must be a float.

Explicit Type Conversion (Type Casting):

This is when you manually convert one data type to another using Python’s built-in functions. You can convert data types such as integers, floats, strings, and more.

Common Type Casting Functions:

int(): Converts a value to an integer.


x = int(5)   # x will be 5
y = int(10.8) # y will be 10
z = int("20") # z will be 20

float(): Converts a value to a float.


x = float(5)     # x will be 5.0
y = float(10.8)   # y will be 10.8
z = float("4")   # z will be 4.0
w = float("5.2") # w will be 5.2

str(): Converts a value to a string.


x = str("Hello") # x will be 'Hello'
y = str(20)    # y will be '20'
z = str(30.0)  # z will be '30.0'

list(): Converts an iterable (e.g., a string or a tuple) to a list.


name = "hello"
my_list = list(name )
print(my_list)  # Output: ['h', 'e', 'l', 'l', 'o']

range to list type conversion: You can convert an range() object to a list.


my_range = range(1, 5)
my_list = list(my_range)
print(my_list)  # Output: [1, 2, 3, 4]

tuple(): Here’s how to convert other data types to a tuple in Python:

String to Tuple: You can convert a string to a tuple where each character becomes an element.


name= "hello"
my_tuple = tuple(name)
print(my_tuple)  # Output: ('h', 'e', 'l', 'l', 'o')

Range to Tuple: You can convert an range() object to a tuple.


my_range = range(1, 5)
my_tuple = tuple(my_range)
print(my_tuple)  # Output: (1, 2, 3, 4)