Convert all string items of a list to integer in Python

In this tutorial, I will show you how to convert all string items of a list to integer items in Python.

It’s better to show an example of what I am going to do in this tutorial:

I will take a list like this: myList = ["1", "-45", "32", "21"]

Then I will convert it to this:  [1, -45, 32, 21]

I hope you got my point. It’s just simple as converting each of the elements to the integer type.

There are multiple ways to do so. The biggest question that may appear is: am I going to convert the list directly or going to store the converted items in a different new list variable? List in Python is mutable so we can make changes to the item values easily.

Convert items of a list to string in Python using built-in int() function

Here, I am going to use this built-in function with list comprehension.

myList = ["1", "-45", "32", "21"]
print(myList)
print([int(x) for x in myList])

Output:

['1', '-45', '32', '21']
[1, -45, 32, 21]

As we can see in the first print line it is showing the elements as string and in the second line it got printed as integer items.

You can check more at: List and dictionary comprehension in Python

The better approach to see the type of elements:

myList = ["1", "-45", "32", "21"]
print(myList)
print(type(myList[0]))
intList = [int(x) for x in myList]
print(intList)
print(type(intList[0]))

Output:

['1', '-45', '32', '21']
<class 'str'>
[1, -45, 32, 21]
<class 'int'>

print(type(myList[0]))This line is used just to show the type of the element.

List element string to int in Python using eval()

The code is almost the same as the previous one but here I am using eval() instead of int().

myList = ["1", "-45", "32", "21"]
print(myList)
print(type(myList[0]))
intList = [eval(x) for x in myList]
print(intList)
print(type(intList[0]))

Output:

['1', '-45', '32', '21']
<class 'str'>
[1, -45, 32, 21]
<class 'int'>

list(map()) to convert list string elements to integer

I will use the below line of code:

list(map(int, myList))
myList = ["1", "-45", "32", "21"]
print(myList)
print(type(myList[0]))
intList = list(map(int, myList))
print(intList)
print(type(intList[0]))

Output:

['1', '-45', '32', '21']
<class 'str'>
[1, -45, 32, 21]
<class 'int'>

Using NumPy to convert string list to int list

This time, I am going to use NumPy.

list(numpy.array(myList, dtype=int))

This line is the key point of our code.

import numpy
myList = ["1", "-45", "32", "21"]
print(myList)
print(type(myList[0]))
intList = list(numpy.array(myList, dtype=int))
print(intList)
print(type(intList[0]))
Output:
['1', '-45', '32', '21']
<class 'str'>
[1, -45, 32, 21]
<class 'numpy.int64'>

The type of converted elements is numpy.int64.

I put this method at the last as I can’t say this as a pure int list.

Leave a Reply

Your email address will not be published. Required fields are marked *