Converting a List of Strings into an Integer in Python

This article will explain how to convert list items to integers using Python. We will see some code examples and also the pitfalls that one should be aware of while converting lists to integer. …

Updated November 21, 2023

This article will explain how to convert list items to integers using Python. We will see some code examples and also the pitfalls that one should be aware of while converting lists to integer.

1. Basic Conversion

To convert a list item to an integer, you can use the built-in int() function in python. Here is how it works:

# List of strings
str_list = ["23", "45", "67"]

# Converting each string to int
int_list = [int(i) for i in str_list]
print(int_list)  # Output: [23, 45, 67]

This is a basic conversion process. Note that this will throw an error if the list contains non-numeric strings.

2. Handling Non-Numeric Strings

If your list can contain non-numeric strings or empty spaces, you should use exception handling while converting to integer:

str_list = ["23", "45", ", "abc"]
int_list = []
for i in str_list:
    try: 
        int_list.append(int(i))
    except ValueError:
        pass # Or you can handle this in some other way
print(int_list)  # Output: [23, 45]

This will skip non-numeric strings and empty spaces from the conversion process.

3. Handling Possible Errors

It’s also a good idea to use isinstance() function for checking if a value is an integer or not before converting it:

str_list = ["23", "45", ", None, True]
int_list = []
for i in str_list:
    if isinstance(i, int):  # Skip if the element is already a number
        continue        
    elif not isinstance(i, (str, type(None))):  # Ignore non-numeric types
        raise ValueError("Invalid value for conversion to integer: " + str(i))
    else:   # Convert numeric strings and None to int
        try: 
            int_list.append(int(i))
        except ValueError as e:
            print("Conversion failed:", str(e))
print(int_list)  # Output: [23, 45, None]

This will raise a ValueError exception if the element cannot be converted to an integer.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!