How to convert list of intable strings to int [duplicate]

I’d use a custom function:

def try_int(x):
    try:
        return int(x)
    except ValueError:
        return x

Example:

>>> [try_int(x) for x in  ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]

Edit: If you need to apply the above to a list of lists, why didn’t you converted those strings to int while building the nested list?

Anyway, if you need to, it’s just a matter of choice on how to iterate over such nested list and apply the method above.

One way for doing that, might be:

>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]

You can obviusly reassign that to list_of_lists:

>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]

Leave a Comment