Conversion of Integer String to list in Python

Converting an integer string to a list is a common task in Python programming. An integer string contains numeric characters (like "123" or "1 2 3"), and we want to transform it into a list of integers. Python provides several built-in methods to accomplish this conversion efficiently.

Using map() and split() Functions

The most common approach uses map() and split() to convert space-separated integers ?

int_str = "1 2 3 4 5"
result = list(map(int, int_str.split()))
print("Converted list:", result)
Converted list: [1, 2, 3, 4, 5]

Using List Comprehension

For strings without spaces, list comprehension splits each character into separate integers ?

int_str = "4573"
result = [int(digit) for digit in int_str]
print("Converted list:", result)
Converted list: [4, 5, 7, 3]

Using for Loop with split()

A traditional approach using a for loop to iterate through split values ?

int_str = "20 40 61 82 10"
result = []
for item in int_str.split():
    result.append(int(item))
print("Converted list:", result)
Converted list: [20, 40, 61, 82, 10]

Using while Loop for Complex Parsing

When dealing with negative numbers or mixed formats, a while loop provides more control ?

int_str = "14 -15 17 18"
result = []
i = 0
while i < len(int_str):
    if int_str[i].isdigit() or int_str[i] == '-':
        num = ""
        while i < len(int_str) and (int_str[i].isdigit() or int_str[i] == '-'):
            num += int_str[i]
            i += 1
        if num and num != '-':
            result.append(int(num))
    else:
        i += 1
print("Converted list:", result)
Converted list: [14, -15, 17, 18]

Using NumPy Module

NumPy's fromstring() method provides efficient conversion for numerical data ?

import numpy as np

int_str = "11 16 17 14 89"
result = np.fromstring(int_str, dtype=int, sep=' ').tolist()
print("Converted list:", result)
Converted list: [11, 16, 17, 14, 89]

Comparison of Methods

Method Best For Performance Complexity
map() + split() Space-separated integers Fast Low
List comprehension Single digits without spaces Fast Low
For loop Learning purposes Medium Medium
While loop Complex parsing needs Slower High
NumPy Large datasets Very fast Low

Conclusion

Use map() with split() for space-separated integers, and list comprehension for individual digit conversion. NumPy is ideal for large datasets, while custom loops provide flexibility for complex parsing requirements.

Updated on: 2026-03-27T12:17:22+05:30

737 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements