Lists are one of the most used container objects in python programming. In this article, we will discuss various approaches to convert a list of strings to a list of integers in python.
List of Strings to List of Integers Using For Loop
We can convert a list of strings to a list of integers using a for loop and the int()
function. For this, we will first create an empty list named output_list
. After that, we will traverse the list of strings using the for loop. While traversal, we will convert each string element to an integer using the int()
function. After that, we will add the integer to the output_list
using the append()
method. The append()
method, when invoked on a list, accepts an element as an input argument and appends the element to the list.
After execution of the for loop, we will get a list of integers as output_list
. You can observe this in the following example.
myList = ["1", "2", "3", "4", "5"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
If there are elements in the list that cannot be converted to an integer, the program will run into the ValueError
exception as shown below.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
value = int(element)
ValueError: invalid literal for int() with base 10: 'PFB'
Here, you can see that the string “PFB” could not be converted to an integer. Due to this, the program raises the ValueError
exception.
To handle the error, you can use exception handling in python using the try-except blocks. Inside the for loop, we will convert the element to an integer using the int()
function in the try block before appending it to the output_list
. In the except block, we will print each element that cannot be converted to an integer. In this way, we will get a list of integers using only those elements from the input list that can be directly converted to an integer using the int()
function.
You can observe this in the following example.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = []
for element in myList:
try:
value = int(element)
output_list.append(value)
except ValueError:
print("{} cannot be converted to integer.".format(element))
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
PFB cannot be converted to integer.
The input list is: ['1', '2', '3', '4', '5', 'PFB']
The output list is: [1, 2, 3, 4, 5]
List of Strings to List of Integers Using List Comprehension
Instead of the for loop, we can use list comprehension and the int()
function to convert a list to strings to a list of integers as follows.
myList = ["1", "2", "3", "4", "5"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
Using the list comprehension has a restriction that we won’t be able to handle errors if any element of the input list is not converted to an integer because we cannot use exception handling inside the list comprehension syntax.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <module>
output_list = [int(element) for element in myList]
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <listcomp>
output_list = [int(element) for element in myList]
ValueError: invalid literal for int() with base 10: 'PFB'
List of Strings to List of Integers Using map() Function
The map()
function is used to apply a function to all of the elements of an iterable object. The map()
function takes a function as its first input argument and an iterable object as the second input argument. It executes the function given in the input argument with all the elements of the input iterable object one by one and returns an iterable object with the output values.
To convert a list of strings to a list of integers, we will pass the int()
function as the first input argument to the map()
function and the list of strings as the second input argument. After execution, we will get a list of integers as shown below.
myList = ["1", "2", "3", "4", "5"]
output_list = list(map(int, myList))
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
If we use this approach, we will not be able to avoid or handle exceptions if the input list contains a string that cannot be converted to an integer.
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = list(map(int, myList))
print("The input list is:", myList)
print("The output list is:", output_list)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <module>
output_list = list(map(int, myList))
ValueError: invalid literal for int() with base 10: 'PFB'
Conclusion
In this article, we have discussed three ways to convert a list of strings to a list of integers in python. To know more about strings, you can read this article on string formatting in python. You might also like this article on dictionary comprehension in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.