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.
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).
Data cleaning pipelines frequently receive mixed raw inputs that must be filtered down to specific numerical data types before running analytical models.
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]
[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.isinstance(True, int): In Python, bool is a subclass of int! isinstance(True, int) returns True. To strictly exclude booleans, check type(x) == int.Use list comprehensions for concise filtering. Next, let's convert text into H4ck3r Sp34k!
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.
`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.
`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.