How do I convert all strings in a list of lists to integers?
Simply use nested comprehension with the int()
function to convert all string elements in a nested list into integers:
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
:
Going retro: Python 2
If you are still working with Python 2, map function can achieve similar results:
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
:
Consistency in data types
If the original data structure includes tuples, slightly tweak the comprehension to preserve the tuple structure:
This will keep your data types consistent and your programs running smoothly!
Was this article helpful?