Convert all strings in a list to int

PythonListInt

Python Problem Overview


In Python, I want to convert all strings in a list to integers.

So if I have:

results = ['1', '2', '3']

How do I make it:

results = [1, 2, 3]

Python Solutions


Solution 1 - Python

Use the map function (in Python 2.x):

results = map(int, results)

In Python 3, you will need to convert the result from map to a list:

results = list(map(int, results))

Solution 2 - Python

Use a list comprehension:

results = [int(i) for i in results]

e.g.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

Solution 3 - Python

If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.

So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)

Output:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']

To also handle iterables inside iterables you can use this helper:

from collections.abc import Iterable, Mapping

def convertEr(iterab):
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance(iterab, str):
        return maybeMakeNumber(iterab)

    if isinstance(iterab, Mapping):
        return iterab

    if isinstance(iterab, Iterable):
        return  iterab.__class__(convertEr(p) for p in iterab)


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ("0", "8", {"15", "things"}, "3.141"), "types"]

converted = convertEr(data)
print(converted)

Output:

['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',  (0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order

Solution 4 - Python

You can easily convert string list items into int items using loop shorthand in python

Say you have a string result = ['1','2','3']

Just do,

result = [int(item) for item in result]
print(result)

It'll give you output like

[1,2,3]

Solution 5 - Python

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

e.g.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

Solution 6 - Python

There are several methods to convert string numbers in a list to integers.

In Python 2.x you can use the map function:

>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]

Here, It returns the list of elements after applying the function.

In Python 3.x you can use the same map

>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]

Unlike python 2.x, Here map function will return map object i.e. iterator which will yield the result(values) one by one that's the reason further we need to add a function named as list which will be applied to all the iterable items.

Refer to the image below for the return value of the map function and it's type in the case of python 3.x

map function iterator object and it's type

The third method which is common for both python 2.x and python 3.x i.e List Comprehensions

>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

Solution 7 - Python

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

Solution 8 - Python

You can do it simply in one line when taking input.

[int(i) for i in input().split("")]

Split it where you want.

If you want to convert a list not list simply put your list name in the place of input().split("").

Solution 9 - Python

I also want to add Python | Converting all strings in list to integers

Method #1 : Naive Method

# Python3 code to demonstrate 
# converting list of strings to int 
# using naive method 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using naive method to 
# perform conversion 
for i in range(0, len(test_list)): 
	test_list[i] = int(test_list[i]) 
	

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Method #2 : Using list comprehension

# Python3 code to demonstrate 
# converting list of strings to int 
# using list comprehension 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using list comprehension to 
# perform conversion 
test_list = [int(i) for i in test_list] 
	

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Method #3 : Using map()

# Python3 code to demonstrate 
# converting list of strings to int 
# using map() 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using map() to 
# perform conversion 
test_list = list(map(int, test_list)) 
	

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Output:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Solution 10 - Python

The answers below, even the most popular ones, do not work for all situations. I have such a solution for super resistant thrust str. I had such a thing:

AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']

AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA

[0.0, 0.5, 0.5, 0.1, 0.1, 0.1, 0.1]

You can laugh, but it works.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - PythoncheekenView Answer on Stackoverflow
Solution 2 - PythonChris VigView Answer on Stackoverflow
Solution 3 - PythonPatrick ArtnerView Answer on Stackoverflow
Solution 4 - PythondanialcodesView Answer on Stackoverflow
Solution 5 - Python2RMalinowskiView Answer on Stackoverflow
Solution 6 - PythonShubhank GuptaView Answer on Stackoverflow
Solution 7 - PythonCode CarbonateView Answer on Stackoverflow
Solution 8 - PythonBoruto UzumakiView Answer on Stackoverflow
Solution 9 - PythonMohsin RazaView Answer on Stackoverflow
Solution 10 - PythonWojciech MoszczyńskiView Answer on Stackoverflow