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.
Python code
15 linesdef 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
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
- Return a list of statuses instead of printing: `return [classification(i) for i in data]`
- 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
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.