Converting all strings in list to integers in Python

PythonServer Side ProgrammingProgramming

Sometimes we can have a list containing strings but the strings themselves are numbers and closing quotes. In such a list we want to convert the string elements into actual integers.

With int()

The int function takes in parameters and converts it to integers if it is already a number. So we design a for loop to go through each element of the list and apply the in function. We store the final result into a new list.

Example

 Live Demo

listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using int
res = [int(i) for i in listA]
# Result
print("The converted list with integers : \n",res)

Output

Running the above code gives us the following result −

Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23]

With map and list

The map function can be used to apply int function into every element that is present as a string in the given list.

Example

 Live Demo

listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using map and int
res = list(map(int, listA))
# Result
print("The converted list with integers : \n",res)

Output

Running the above code gives us the following result −

Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23]
raja
Published on 04-Jun-2020 14:45:44
Advertisements