Python
Data Conversion
Lists
Strings to Integers
Programming Techniques

Convert all strings in a list to integers

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The fastest way to convert all strings in a list to integers in Python is list(map(int, string_list)). For more control, use a list comprehension: [int(x) for x in string_list]. Both approaches call int() on each element and raise ValueError if any string cannot be converted. For lists with non-numeric values, filter or handle errors with try/except before converting.

Basic Conversion Methods

map() — Fastest

python
1string_list = ["1", "2", "3", "4", "5"]
2
3int_list = list(map(int, string_list))
4print(int_list)  # [1, 2, 3, 4, 5]

map(int, string_list) applies int() to each element. It returns a map object (lazy iterator), so wrap it in list() to get a list. This is the fastest approach because map is implemented in C.

List Comprehension

python
1string_list = ["10", "20", "30", "40"]
2
3int_list = [int(x) for x in string_list]
4print(int_list)  # [10, 20, 30, 40]

List comprehensions are slightly slower than map but more readable and flexible — you can add conditions or transformations inline.

for Loop

python
1string_list = ["1", "2", "3"]
2int_list = []
3
4for s in string_list:
5    int_list.append(int(s))
6
7print(int_list)  # [1, 2, 3]

Explicit loops are the slowest but most readable for beginners. Use map or comprehensions for better performance.

Handling Non-Numeric Strings

Filter with isdigit()

python
1mixed = ["1", "abc", "3", "4.5", "5", ""]
2
3# isdigit() only passes pure digit strings
4int_list = [int(x) for x in mixed if x.isdigit()]
5print(int_list)  # [1, 3, 5]
6# Note: "4.5" is excluded because isdigit() returns False for decimals

Try/Except for Robust Conversion

python
1mixed = ["1", "abc", "3", "4.5", "5", ""]
2
3def safe_int(s):
4    try:
5        return int(s)
6    except (ValueError, TypeError):
7        return None
8
9int_list = [safe_int(x) for x in mixed]
10print(int_list)  # [1, None, 3, None, 5, None]
11
12# Filter out None values
13int_list = [x for x in int_list if x is not None]
14print(int_list)  # [1, 3, 5]

Convert Floats to Integers

python
1mixed = ["1", "2.5", "3", "4.7"]
2
3# int() fails on "2.5" directly — convert via float first
4int_list = [int(float(x)) for x in mixed]
5print(int_list)  # [1, 2, 3, 4] — truncates toward zero
6
7# Or round
8int_list = [round(float(x)) for x in mixed]
9print(int_list)  # [1, 2, 3, 5] — rounds to nearest

int("2.5") raises ValueError. You must go through float() first: int(float("2.5")).

Different Number Bases

python
1# Hex strings
2hex_strings = ["0xff", "0x1a", "0x2b"]
3ints = [int(x, 16) for x in hex_strings]
4print(ints)  # [255, 26, 43]
5
6# Binary strings
7bin_strings = ["1010", "1100", "1111"]
8ints = [int(x, 2) for x in bin_strings]
9print(ints)  # [10, 12, 15]
10
11# Octal strings
12oct_strings = ["0o17", "0o10", "0o77"]
13ints = [int(x, 8) for x in oct_strings]
14print(ints)  # [15, 8, 63]
15
16# Auto-detect base from prefix (0x, 0b, 0o)
17mixed_bases = ["0xff", "0b1010", "0o17", "42"]
18ints = [int(x, 0) for x in mixed_bases]
19print(ints)  # [255, 10, 15, 42]

NumPy for Large Lists

python
1import numpy as np
2
3string_list = ["1", "2", "3", "4", "5"]
4
5# Convert to NumPy array of integers — much faster for large lists
6int_array = np.array(string_list, dtype=int)
7print(int_array)  # [1 2 3 4 5]
8
9# Or from an existing array
10str_array = np.array(["10", "20", "30"])
11int_array = str_array.astype(int)
12print(int_array)  # [10 20 30]

For lists with 10,000+ elements, NumPy is 5-10x faster because the conversion is vectorized in C.

Performance Comparison

python
1import timeit
2
3strings = [str(i) for i in range(100000)]
4
5# Method 1: map
6timeit.timeit(lambda: list(map(int, strings)), number=100)
7# ~0.8s
8
9# Method 2: list comprehension
10timeit.timeit(lambda: [int(x) for x in strings], number=100)
11# ~1.0s
12
13# Method 3: for loop
14def for_loop():
15    result = []
16    for s in strings:
17        result.append(int(s))
18    return result
19timeit.timeit(for_loop, number=100)
20# ~1.3s
21
22# Method 4: NumPy
23import numpy as np
24timeit.timeit(lambda: np.array(strings, dtype=int), number=100)
25# ~0.4s

Nested Lists

python
1nested = [["1", "2"], ["3", "4"], ["5", "6"]]
2
3# Convert nested list of strings to integers
4int_nested = [[int(x) for x in sublist] for sublist in nested]
5print(int_nested)  # [[1, 2], [3, 4], [5, 6]]
6
7# Flatten and convert
8flat = [int(x) for sublist in nested for x in sublist]
9print(flat)  # [1, 2, 3, 4, 5, 6]

Other Languages

javascript
1// JavaScript
2const strings = ["1", "2", "3"];
3const ints = strings.map(Number);
4console.log(ints);  // [1, 2, 3]
5// Note: Number("") returns 0 and Number("abc") returns NaN
java
1// Java
2List<String> strings = List.of("1", "2", "3");
3List<Integer> ints = strings.stream()
4    .map(Integer::parseInt)
5    .collect(Collectors.toList());

Common Pitfalls

  • int() fails on float strings: int("3.14") raises ValueError. Use int(float("3.14")) to convert via float first, or validate input before converting.
  • Empty strings: int("") raises ValueError. Filter empty strings with [int(x) for x in lst if x] or [int(x) for x in lst if x.strip()].
  • Whitespace in strings: int(" 42 ") works — int() strips leading/trailing whitespace. But int("4 2") (internal space) fails. Use .replace(" ", "") to remove all spaces if needed.
  • Leading zeros: int("007") returns 7 — leading zeros are ignored. But int("08", 8) fails because 8 is not a valid octal digit. Be explicit about the base when converting non-decimal strings.
  • Large numbers: int("99999999999999999999999999999") works — Python integers have arbitrary precision. But converting to NumPy int64 overflows for values beyond 2^63-1. Use dtype=object for arbitrary precision in NumPy.

Summary

  • Use list(map(int, strings)) for the fastest conversion
  • Use list comprehension [int(x) for x in strings] for readability and inline filtering
  • Handle non-numeric strings with try/except or isdigit() filtering
  • Use int(float(x)) for float strings like "3.14"
  • Use int(x, base) for hex, binary, or octal strings
  • For large datasets (10,000+ elements), NumPy's np.array(strings, dtype=int) is fastest

Course illustration
Course illustration

All Rights Reserved.