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.

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

Python code

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

stdout
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

  1. Use a list comprehension for a more concise version: [x for x in items if isinstance(x, (int, float)) and not isinstance(x, bool)]
  2. 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

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.