Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
Python code
29 linesdef extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a mixed list."""
strings = []
for item in items:
if isinstance(item, str):
strings.append(item)
return strings
if __name__ == "__main__":
data = [1, "apple", 3.14, True, "banana", 42, None, "cherry", 2.5, False]
nums = extract_numbers(data)
strs = extract_strings(data)
print(f"Original data: {data}")
print(f"Numbers: {nums}")
print(f"Strings: {strs}")
print(f"Number count: {len(nums)}")
print(f"String count: {len(strs)}")
Output
Original data: [1, 'apple', 3.14, True, 'banana', 42, None, 'cherry', 2.5, False]
Numbers: [1, 3.14, 42, 2.5]
Strings: ['apple', 'banana', 'cherry']
Number count: 4
String count: 3
How it works
The functions extract_numbers and extract_strings each iterate over the input list and use isinstance to check each item's type. For numbers, isinstance(item, (int, float)) catches integers and floats, while not isinstance(item, bool) excludes booleans because bool is a subclass of int in Python. The list numbers accumulates only the numeric values, and strings collects only string items, preserving the original order. Using a simple for loop with append makes the filtering explicit and easy to follow, which is ideal for beginners.
Common mistakes
- Treating booleans as numbers — True and False are int subclasses, so filter with not isinstance(item, bool)
- Forgetting None values that pass no type checks and get silently ignored
- Using type(item) == int instead of isinstance to match subclasses like bool
Variations
- Use a list comprehension for a more concise version: [x for x in items if isinstance(x, (int, float)) and not isinstance(x, bool)]
- Use a single pass with groupby from itertools to build both lists at once
Real-world use cases
- Cleaning rows from a CSV import by separating numeric columns from text columns before processing.
- Filtering log entries where messages contain mixed types and you need only numeric metrics.
- Normalizing JSON payloads that mix numbers and strings so each type gets its own validation path.
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
- Find All Occurrences of an Item in a Python List easy
- Find Duplicate Elements in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.