Learn how to use Python list comprehensions and isinstance() to filter out non-numeric elements from a mixed list.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
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!