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.
Python code
24 linesdef 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
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
- Use a list comprehension with a helper function for shorter code.
- 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
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.