0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert List of Strings to Integers

You can convert a list of strings to integers in Python using list comprehension like [int(x) for x in list_of_strings] or the map(int, list_of_strings) function.
📋

Examples

Input["1", "2", "3"]
Output[1, 2, 3]
Input["10", "20", "30", "40"]
Output[10, 20, 30, 40]
Input[]
Output[]
🧠

How to Think About It

To convert a list of strings to integers, think about changing each string one by one into a number. You can do this by going through the list and applying the conversion to each item, then collecting the results back into a list.
📐

Algorithm

1
Get the list of strings as input.
2
For each string in the list, convert it to an integer.
3
Collect all converted integers into a new list.
4
Return the new list of integers.
💻

Code

python
list_of_strings = ["1", "2", "3"]
list_of_integers = [int(x) for x in list_of_strings]
print(list_of_integers)
Output
[1, 2, 3]
🔍

Dry Run

Let's trace converting ["1", "2", "3"] to integers using list comprehension.

1

Start with list

list_of_strings = ["1", "2", "3"]

2

Convert each string

int("1") = 1, int("2") = 2, int("3") = 3

3

Create new list

list_of_integers = [1, 2, 3]

Original StringConverted Integer
"1"1
"2"2
"3"3
💡

Why This Works

Step 1: Why use int()

The int() function changes a string that looks like a number into an actual number.

Step 2: Why list comprehension

List comprehension applies int() to each string quickly and collects results in a new list.

Step 3: Alternative with map

The map() function can also apply int to each item, returning a map object that can be converted to a list.

🔄

Alternative Approaches

Using map() function
python
list_of_strings = ["4", "5", "6"]
list_of_integers = list(map(int, list_of_strings))
print(list_of_integers)
This method is concise and uses built-in map, but returns a map object that needs conversion to list.
Using a for loop
python
list_of_strings = ["7", "8", "9"]
list_of_integers = []
for s in list_of_strings:
    list_of_integers.append(int(s))
print(list_of_integers)
This is more verbose but clear for beginners and easy to debug.

Complexity: O(n) time, O(n) space

Time Complexity

The code processes each string once, so time grows linearly with the list size.

Space Complexity

A new list of integers is created, so space also grows linearly with input size.

Which Approach is Fastest?

List comprehension and map() have similar speed; map() may be slightly faster in some cases but both are efficient.

ApproachTimeSpaceBest For
List ComprehensionO(n)O(n)Readability and Pythonic style
map() FunctionO(n)O(n)Concise code and functional style
For LoopO(n)O(n)Beginners and step-by-step debugging
💡
Use list comprehension for a clean and fast way to convert all strings to integers.
⚠️
Trying to convert strings with non-numeric characters without error handling causes a ValueError.