How to Safely Convert a List of Strings to Integers in Python
Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.
Python code
17 linesdef safe_to_int(values):
"""Safely convert a list of strings to integers, skipping invalid entries."""
result = []
errors = []
for value in values:
try:
result.append(int(value))
except (ValueError, TypeError):
errors.append(value)
return result, errors
if __name__ == "__main__":
strings = ["42", "3.14", "0", "-7", "abc", "", None, " 8 "]
numbers, failed = safe_to_int(strings)
print(f"Converted: {numbers}")
print(f"Skipped: {failed}")
Output
Converted: [42, 0, -7, 8]
Skipped: ['3.14', 'abc', '', None, ' 8 ']
How it works
The safe_to_int function iterates over each string and attempts int(value). When the conversion succeeds, the integer is appended to result. When it raises ValueError or TypeError, the original value is recorded in errors. This pattern keeps the valid numbers and the invalid entries separate, making it easy to handle both. The ValueError covers strings that don't represent an integer (like "abc" or "3.14"), while TypeError catches None or non-string values. The loop uses a simple for with an explicit append, which is clear and easy to extend with additional logic per item.
Common mistakes
- Forgetting to catch TypeError for None or non-string values
- Using float conversion instead of int when you want whole numbers
- Ignoring whitespace: int() handles leading/trailing spaces, but some validators strip them first
- Not preserving the original invalid values for logging or debugging
Variations
- Use a list comprehension with a helper function: `[int(s) for s in strings if s.isdigit()]` (but this fails on whitespace or signs)
- Use `map(int, filter(str.isdigit, strings))` for a functional approach
Real-world use cases
- Parsing CSV or user input where some fields may be empty or malformed, and you need to keep the valid numbers.
- Cleaning data from an API response before loading it into a database or metrics system.
- Batch processing of CLI arguments or configuration lists where invalid entries should not crash the script.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.