Convert String Array to Int Array in Python

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.

Output:

[2, 4, 6, 11]

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,

Output:

[2, 4, 6, 11]

Using for loop with eval() function

Use the eval() function to convert string array to int array in Python

Output:

[2, 4, 6, 11]

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.

Using the map() with list() function

To convert string array to in array in Python:

  • Use the map() function to apply the int() function to all elements of the array.
  • Use the list() function to convert the map type object to a list.

Output:

[2, 4, 6, 11]

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.

Was this post helpful?

Leave a Reply

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