Converting all Strings in a List to Integers - Python
We are given a list of strings containing numbers and our task is to convert these strings into integers. For example, if the input list is ["1", "2", "3"] the output should be [1, 2, 3]. Note: If our list contains elements that cannot be converted into integers such as alphabetic characters, strings or special symbols, trying to convert them using int() will raise a ValueError or Invalid Literal Error. Let's discuss various ways to convert all string elements in a list to integers in Python.
Using map()
map() function applies a given function to all elements in an iterable. Here, we use map(int, a) to convert each string in the list to an integer.
a = ['2', '4', '6', '8']
b = list(map(int, a))
print(b)
Output
[2, 4, 6, 8]
Explanation:
- map(int, a) applies the int() function to every item in the list 'a'.
- list(map(int, a)) converts the result of map() into a list.
Using list comprehension
List comprehension provides a more Pythonic and concise way to convert a list of strings to integers as it combines the conversion and iteration into a single line of code.
a = ['2', '4', '6', '8']
b = [int(item) for item in a]
print(b)
Output
[2, 4, 6, 8]
Explanation:
- int(item) converts each string in the list to an integer.
- [int(item) for item in a] this list comprehension goes through each element (item) of 'a', applies int() and collects the results in a new list.
Using a loop
In this approach we iterate over the list using a loop (for loop) and convert each string to an integer using the int() function.
a = ['2', '4', '6', '8']
for i in range(len(a)):
a[i] = int(a[i])
print(a)
Output
[2, 4, 6, 8]
Explanation:
- for i in range(len(a)) iterates over the indices of the list a.
- a[i] = int(a[i]) converts each string at index i to an integer and updates the list in place.
Related Articles:
- Python map() function
- List Comprehension in Python
- Python For Loops
- Convert integer to string in Python
- Convert String to Integers in Python
- Convert number to list of integers in Python
- Integers String to Integer List in Python