How to convert Python list elements to integers?

Cast list elements to int in Python

You can easily convert all elements in your Python list from string to int by using a simple list comprehension:

int_lst = [int(e) for e in str_lst]

Problem

We have an array of string elements representing numbers and we would like to convert those to the integer data type so that we can use them in our Data Analysis work.

Converting list to integer in Python

Assume that you have the following Python list / array that is made of the following strings:

#Python3
grade_lst = ["100", "90", "80", "78", "67"]

We can cast the list string elements to the integer type by using the following methods:

Using a list comprehension

Probably the most elegant method to apply logic to a list elements is the so-called Python list comprehension.

    grade_int = [int(e) for e in grade_lst]
    print (grade_int)

    Using a for loop

    An alternative method is to loop through the list, cast the elements and append them into a new list.

    grade_int = []
    for e in grade_lst:
        grade_int.append(int(e))
    print (grade_int)

    Using Numpy

    We will use the third party numpy (Numerical Python) library. Note that you will need to import the Numpy library to your Python IDE (Integrated development environment – PyCharm, VS Code, Jupyter and so forth) before using it.

    import numpy as np
    grade_int  = list(np.array(grade_lst, int))
    print (grade_int)

    Using the map function

    Another strong capability in Python functional programming, is the ability to amp a function to an iterable (such as a list / array). In the code below, map helps to apply the int function to the element of our list, which are then in turn kept as a new list:

    grade_int = list(map(int, grade_lst))
    print (grade_int)

    Output

    All the methods detailed above will render the same result:

    [100, 90, 80, 78, 67]

    Follow up learning

    How to divide a list to sub lists according to a condition?