• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / List of Strings to List of Integers in Python

List of Strings to List of Integers in Python

Author: Aditya Raj
Last Updated: April 1, 2022

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. 

Related

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.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us