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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

17 lines
Python 3.9+
def 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

stdout
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

  1. Use a list comprehension with a helper function: `[int(s) for s in strings if s.isdigit()]` (but this fails on whitespace or signs)
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.