1.2 Type casting

Working with variables

Types in Python are inferred. But sometimes, we need to convert one type to another. This is called typecasting. It is especially important when we are working with user input, which is always a string. While in data analytics, we do not usually work with user input, we are working with data that is read from a file and might not always be as clean as we want it to be. Sometimes the types are not clear or are mixed up due to clumsy implementation. Type casting helps us to clean up the data and make it usable. In addition, typecasting is especially useful when we are doing math on the data—something we will do frequently.

Python infers the type in the following ways:

We can demonstrate this by using the type() function. The type() function returns the type of the data passed into the function (or the parentheses).

a_number = 3
print("a_number is of type: ", type(a_number))

a_float = 3.0
print("a_float is of type: ", type(a_float))

a_string = "3"
print("a_string is of type: ", type(a_string))
a_number is of type:  <class 'int'>
a_float is of type:  <class 'float'>
a_string is of type:  <class 'str'>

You have already been introduced to typecasting in the previous section. We used the int(), float(), and str() functions to explicitly create a string or a float or an integer. This is the same way we can convert a string to a float or an integer.

We can use these type-casting functions on variables as well.

a = "3"
b = "5"

Both a and b are strings (we know that because of the quotation marks), so we cannot do any math with them.

print("concatination: ", a + b) # this will concatenate the two strings
concatination:  35

We get 35 because adding strings together is called concatenation.

For instance, if we create two strings: “x” and “y” and use the addition operator, it will concatenate them together.

print("another example of concatenation: ", "x" + "y") 
another example of concatenation:  xy

We can convert them to integers to do math. Here we can create a variable c that is the sum of a and b by coercing a and b into integers using the int() function.

Through coercing (or type casting) into integers, the two integers will be added together mathematically.

c = int(a) + int(b) 

print("sum of a and b: ", c)
sum of a and b:  8

We can do the same thing with complex data types as well. Every data type has its own function that will create that data type in the same way as we showed above.

Data Type Function
Integer int()
Float float()
String str()
Boolean bool()
List list()
Tuple tuple()
Set set()
Dictionary dict()
# Example of type Casting
a_list = ["1", "2", "3"]
b_list = ["a", "b", "c"]

c = set(a_list)
d = tuple(b_list)
e = dict(zip(a_list, b_list))  # creates a dictionary from two lists
print("set of a_list: ", c)
print("tuple of b_list: ", d)
set of a_list:  {'1', '3', '2'}
tuple of b_list:  ('a', 'b', 'c')

Coercing Data Types (Type Casting)

Python has also created various functions to convert data types. These functions are called type casting functions. They allow us to convert one data type to another. For example, we can use the int() function to convert a float to an integer, or the str() function to convert an integer to a string.

Type casting is very important in programming. There are many reasons to cast a type to another type. The most frequent of those is to accept input from the user. Inputs are always strings. For instance, the input() function takes in user input and returns a string. To accept a number, you must convert it to the desired type. We can do this with built-in Python functions.

Function Explanation
int() Converts to an integer
float() Converts to a floating point
str() Converts to a string
bool() Converts to a boolean
list() Converts to a list
tuple() Converts to a tuple
set() Converts to a set
dict() Converts to a dictionary

Previously we learned about these functions as explicit ways to create each of the data types. However, they can also be used to convert between data types. For example,

Example

age = input("Enter your age: ")
age = int(age)

# or

age = int(input("Enter your age: "))

There are other applications as well. For example, you may want to convert a number to a string to concatenate it with another string. Or convert a list to a tuple or vice versa. You can easily do that.

age = 20
my_list = [1, 2, 3, 4, 5]
my_tuple = (6, 7, 8, 9, 10)
string = "Age is a construct"

print("age is", str(age))
print("converted list is", tuple(my_list))
print("converted tuple is", list(my_tuple))
print("string to list", list(string)) # not advisable
print("string to tuple", tuple(string)) # not advisable
age is 20
converted list is (1, 2, 3, 4, 5)
converted tuple is [6, 7, 8, 9, 10]
string to list ['A', 'g', 'e', ' ', 'i', 's', ' ', 'a', ' ', 'c', 'o', 'n', 's', 't', 'r', 'u', 'c', 't']
string to tuple ('A', 'g', 'e', ' ', 'i', 's', ' ', 'a', ' ', 'c', 'o', 'n', 's', 't', 'r', 'u', 'c', 't')

The last two examples are not advisable because they will convert the string to a list of characters or a tuple of characters. There is no control over the conversion. In such circumstances, you should use the split() function to create a list or if you want to create a tuple, split() the string and then convert the list to a tuple with tuple().

But this demonstrates the power of type casting in Python. We can transform any data type into another data type easily. It is an essential in Python.