Convert a list of strings into a list of integers in Python
This post will discuss how to convert a list of strings into a list of integers in Python.
For example, list ["1", "2", "3", "4", "5"] should be converted into list [1, 2, 3, 4, 5].
1. Using map() function
The recommended solution is to call the built-in function map() to efficiently convert a list of strings into a list of integers. It applies the specified function to every item of the list, yielding the results. Since it returns an iterator, convert the result to a list. This function is demonstrated below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': strings = ["1", "2", "3", "4", "5"] nums = list(map(int, strings)) print(nums) # prints [1, 2, 3, 4, 5] |
Note that the above code creates a new list. You can mutate the existing list in-place by assigning to the slice [:], as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': nums = ["1", "2", "3", "4", "5"] nums[:] = list(map(int, nums)) print(nums) # prints [1, 2, 3, 4, 5] |
2. Using List Comprehension
Another approach is to use list comprehension. List comprehension is often used in Python to construct a new list, where each list element results from some operation applied to each member of an iterable.
Here’s a working example using list comprehension:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': strings = ["1", "2", "3", "4", "5"] nums = [int(s) for s in strings] print(nums) # prints [1, 2, 3, 4, 5] |
That’s all about converting a list of strings into a list of integers in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)