How to Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

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

Python code

24 lines
Python 3.9+
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    result.append(float(item))
                else:
                    result.append(int(item))
            except ValueError:
                result.append(item)
        else:
            result.append(item)
    return result

if __name__ == "__main__":
    sample = [10, 3.14, "42", "3.5", "hello", 7, "2.718"]
    converted = convert_data(sample)
    print("Original:", sample)
    print("Converted:", converted)
    print("Types:", [type(x).__name__ for x in converted])

Output

stdout
Original: [10, 3.14, '42', '3.5', 'hello', 7, '2.718']
Converted: ['10', '3.14', 42, 3.5, 'hello', '7', 2.718]
Types: ['str', 'str', 'int', 'float', 'str', 'str', 'float']

How it works

The function iterates over each item in the input list and checks its type. For integers and floats, it converts them to strings. For strings, it attempts to convert to float if a dot is present, otherwise to int; if that fails, it keeps the original string. For other types, it leaves them unchanged. This demonstrates a common pattern of type coercion and graceful error handling within a loop.

Common mistakes

  • Assuming all strings are numeric without checking for ValueError.
  • Forgetting that bool is a subclass of int, so booleans will be converted to '0' or '1'.
  • Using bare except statements that hide unexpected errors.
  • Not preserving the original value when conversion fails.

Variations

  1. Use a list comprehension with a helper function for shorter code.
  2. Use a decorator to memoize conversion results for repeated calls.

Real-world use cases

  • Cleaning mixed-type data from CSV imports before feeding into a database.
  • Parsing user input from forms where fields may be numbers or text.
  • Normalizing values from an API response that returns number-like strings.

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.