Convert list of numerical string to list of Integers in Python

PythonServer Side ProgrammingProgramming

For data manipulation using python, we may come across scenario where we have strings containing numbers in a list. To be able to make calculations, we will need to change the strings into numbers. In this article we will see the ways to change the strings into numbers inside a list.

With int

The int function can be applied to the string elements of a list converting them to integers . We have to carefully design the for loops to go through each element and get the result even if there are multiple strings inside a single element.

Example

 Live Demo

listA = [['29','12'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use int
res = [[int(n) for n in element] for i in listA for element in i]
# Result
print("The numeric lists: ",res)

Output

Running the above code gives us the following result −

Given list A: [['29', '12'], ['25'], ['70']]
The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]

With map

We can also use the map function which will apply a given function again and again to each parameter that is supplied to this function. We create a for loop which fetches the elements form each of the inner lists. This approach does not work if the inner lists have multiple elements inside them.

Example

 Live Demo

listA = [['29'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use map
res = [list(map(int, list(elem[0]))) for elem in listA if elem ]
# Result
print("The numeric lists: ",res)

Output

Running the above code gives us the following result −

Given list A: [['29'], ['25'], ['70']]
The numeric lists: [[2, 9], [2, 5], [7, 0]]
raja
Published on 20-May-2020 14:22:00
Advertisements