Convert all strings in a list to int Convert all strings in a list to int python python

Convert all strings in a list to int


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))


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]


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