Table of Contents
This tutorial will demonstrate how to convert string array to int array in Python.
Using the for loop with int() function
To convert string array to int array in Python:
- Use the
for
loop to loop through the array. - Use the
int()
function to convert each element to an integer in every iteration.
See the code below.
1 2 3 4 5 6 7 |
lst = ['2','4','6','11'] lst_int = [] for i in lst: lst_int.append(int(i)) print(lst_int) |
Output:
In the above example, we iterated over a list and converted each element individually to an integer using the int()
function. Each element was appended to an empty list using the append()
function.
We can perform the above operation more efficiently by using the list comprehension technique. This method is used to create a list using a for
loop in a single line of code.
For example,
1 2 3 4 5 |
lst = ['2','4','6','11'] lst_int = [int(i) for i in lst] print(lst_int) |
Output:
Using for loop with eval()
function
Use the eval()
function to convert string array to int array in Python
1 2 3 4 5 |
lst = ['2','4','6','11'] lst_int = [eval(i) for i in lst] print(lst_int) |
Output:
The eval()
function accepts a Python string and evaluates it as a Python expression. We can use it in place of the int()
function in the previous method.
Further reading:
Using the map()
with list() function
To convert string array to in array in Python:
- Use the
map()
function to apply theint()
function to all elements of the array. - Use the
list()
function to convert themap
type object to a list.
1 2 3 4 5 |
lst = ['2','4','6','11'] lst_int = list(map(int,lst)) print(lst_int) |
Output:
The map()
function can be used to apply the int()
function to all the elements of the array. In Python 3, the map()
function returns a map
type object which can be converted to a list. In Python 2, this function directly returns a list.
Conclusion
To conclude, we discussed several methods to convert string array to int array in Python.
In the first method, we used a for
loop to iterate over the array and convert each element to an integer using the int()
function. This can be achieved efficiently using the list comprehension technique.
In the second method, we replaced the int()
function with the eval()
function. In the final method, we discussed the use of the map()
function to apply the int()
function to every element of the array.
That’s all about how to convert String array to int array in Python.