Explain Codes LogoExplain Codes Logo

How do I convert all strings in a list of lists to integers?

python
dataframe
pandas
list-comprehension
Anton ShumikhinbyAnton Shumikhin·Dec 1, 2024
TLDR

Simply use nested comprehension with the int() function to convert all string elements in a nested list into integers:

nested_list = [['1', '2'], ['3', '4']] integers = [[int(n) for n in inner] for inner in nested_list] # voila! strings converted to ints

So integers will be [[1, 2], [3, 4]].

Dealing with non-numeric strings

If your data might contain non-numeric strings or accidental characters, you'll need to ensure your code is error-proof. Use str.isdigit() to filter out non-numeric strings and prevent a ValueError:

integers = [[int(n) for n in sublist if n.isdigit()] for sublist in nested_list] # ninja code

Going retro: Python 2

If you are still working with Python 2, map function can achieve similar results:

integers = map(lambda sublist: map(int, sublist), nested_list) # Reverse the polarity of the neutron flow!

Note the difference in Python 3, where map returns a map object, not a list. So remember to use list() for such conversions in Python 3!

Tackle strings with decimal points or currency symbols

For strings with decimal points, or even currency symbols, use the float() function, and then convert to int:

integers = [[int(float(n.strip('$'))) for n in sublist] for sublist in nested_list] # Who likes floating point anyway?

Consistency in data types

If the original data structure includes tuples, slightly tweak the comprehension to preserve the tuple structure:

tuples = [(1, '2'), ('3', 4)] int_tuples = [tuple(int(n) if isinstance(n, str) else n for n in inner) for inner in tuples] # tuple-mania

This will keep your data types consistent and your programs running smoothly!