Filter Out Strings from a List
Quick Overview
`isinstance(x, int)` returns `True` for a `bool`, because `bool` subclasses `int` in Python. Filtering for numbers without excluding booleans quietly keeps `True` and `False` in the result.
Deep Dive
1. The Challenge: Data Cleaning
Create a function filter_list(lst) that takes a list of non-negative integers and strings and returns a new list with the strings filtered out (retaining only integers).
2. Why It Matters
Data cleaning pipelines frequently receive mixed raw inputs that must be filtered down to specific numerical data types before running analytical models.
3. The Python Solution
Use a List Comprehension combined with isinstance(item, int) or type(item) == int:
def filter_list(lst):
return [x for x in lst if isinstance(x, int)]
# Testing our function
print(filter_list([1, 2, "a", "b"])) # Output: [1, 2]
print(filter_list([1, "a", "b", 0, 15])) # Output: [1, 0, 15]
print(filter_list([1, 2, "aasf", "1", "123", 123])) # Output: [1, 2, 123]
4. List Comprehension Syntax Breakdown
[expression for item in iterable if condition]:
for x in lst: Iterates through every item.if isinstance(x, int): Filters items keeping only integers (excluding strings and booleans if strictly typed).x: Collects matched elements into a new list.
5. Common Mistakes
- Checking
isinstance(True, int): In Python,boolis a subclass ofint!isinstance(True, int)returnsTrue. To strictly exclude booleans, checktype(x) == int.
6. Next Steps
Use list comprehensions for concise filtering. Next, let's convert text into H4ck3r Sp34k!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.