How to check list items by type and emptiness in Python

Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.

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

Python code

15 lines
Python 3.6+
def check_data(data):
    """Check each item in a list and print whether it's valid."""
    for i, item in enumerate(data):
        if item is None or item == "":
            status = "empty"
        elif isinstance(item, (int, float)):
            status = "number"
        else:
            status = "text"
        print(f"Item {i}: {item!r} -> {status}")


if __name__ == "__main__":
    sample = ["hello", 42, None, "", 3.14, "world", 0]
    check_data(sample)

Output

stdout
Item 0: 'hello' -> text
Item 1: 42 -> number
Item 2: None -> empty
Item 3: '' -> empty
Item 4: 3.14 -> number
Item 5: 'world' -> text
Item 6: 0 -> number

How it works

The enumerate function yields both the index and the value, so you get the position and the item in one loop. The isinstance check catches both integers and floats in one condition, so 0 is correctly classified as a number. None and empty strings are caught first with an is and equality check, so they never fall through to the type checks. The !r in the f-string calls repr on the value, which shows quotes around strings and makes None visible instead of blank.

Common mistakes

  • Using `item == None` instead of `item is None` — identity check is faster and semantically correct for singleton None
  • Forgetting that `0` is a valid number — it must be checked against `is None` and `== ""` before the numeric test
  • Using `type(item) == int` which misses floats — `isinstance(item, (int, float))` covers both

Variations

  1. Return a list of statuses instead of printing: `return [classification(i) for i in data]`
  2. Use a match statement (Python 3.10+) to classify values more expressively

Real-world use cases

  • Validating rows in a spreadsheet export before inserting into a database schema that distinguishes numeric from text columns.
  • Sanitizing user-submitted form fields to log which inputs were empty versus invalid before persisting data.
  • Classifying mixed-type log entries or CSV records to route them into separate processing queues.

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.