# Convert a List of strings to a List of Integers in Python

This tutorial will discuss about unique ways to convert a list of strings to a list of integers in Python.

## Introduction

Suppose we have a list of strings,

```listOfStrs = ["11", "12", "22", "45", "19"]
```

All strings in the list, can be converted into an integers. Therefore, we want to convert all these strings to ints and create a new list of intgers like,

```[11, 12, 22, 45, 19]
```

We will also look a scenario, where we have a list with some non-numeric strings like,

```listOfStrs = ["11", "12", "abc", "45LLP89", "19"]
```

In this scenario, we want to convert only numeric strings in this list to list of integers. We can just skip the non-numeric strings. Like,

```[11, 12, 19]
```

Let’s see how to do that.

## Convert List of strings to list of integers

Loop through all string elements in list, and call int() function on each string to convert it to an integer. Do, all this in a List Comprehension, and it will return a list of integers. This way we can convert a list of strings to a list of integers.

Let’s see the complete example,

```listOfStrs = ["11", "12", "22", "45", "19"]

# Convert a list of strings to a list of integers
listOfInts = [int(strValue) for strValue in listOfStrs]

print(listOfInts)
```

Output

```[11, 12, 22, 45, 19]
```

## What if list has some non numeric strings?

In the above example, we assumed that all string elements in list contains only digits. If you list has strings that has anything other than digits, then the above code can give ValueError. For this scenario, its better to remove non numeric characters from strings first or just skip them. Like this,

Let’s see the complete example,

```listOfStrs = ["11", "12", "abc", "45LLP89", "19"]

# Convert a list of strings to a list of integers
listOfInts = [int(strValue) for strValue in listOfStrs if strValue.isnumeric()]

print(listOfInts)
```

Output

```[11, 12, 19]
```

## Summary

We learned how to convert a list of strings to a list of ints in Python.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top