Python Workout 06: String Filter

Level of Difficulty:

Objective: This workout provides practice in creating functions to implement a filter.

Problem: Create a function that takes a list of non-negative integers and strings and return a new list without the strings.

Examples:

filter_list([1, 2, “a”, “b”]) ➞ [1, 2]

filter_list([1, “a”, “b”, 0, 15]) ➞ [1, 0, 15]

filter_list([1, 2, “aasf”, “1”, “123”, 123]) ➞ [1, 2, 123]

Submission

Simply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Monday April 17, 2023, and the author’s solution will be posted on Sunday April 23, 2023.

1 Like

def filter_list(mixedlist):
filteredlist=[]
for i in mixedlist:
if type(i) == int:
filteredlist.append(i)
return filteredlist

2 Likes

Great job @Neb

[i for i in a if type(i)==int]

1 Like
def filter_integers(lst):
    return [x for x in lst if isinstance(x, int) and x >= 0]

1 Like

My solution for Python Workout 06:

Solution
""" 
Problem: Create a function that takes a list
of non-negative integers and strings and return
a new list without the strings.
"""


def filter_list(value: list) -> list:
    return [i for i in value if type(i) == int and i >= 0]


print(filter_list([1, 2, "a", "b"]))
print(filter_list([1, "a", "b", 0, 15]))
print(filter_list([1, 2, "aasf", "1", "123", 123]))
Terminal

image

1 Like

Answer
list1 = [1, 2, “a”, “b”]
list2 = [1, “a”, “b”, 0, 15]
list3 = [1, 2, “aasf”, 1, 123, 123]

Summary
def is_list_type(my_list):
    newlist = []
    for i in my_list:
        if isinstance(i, int) and i >= 0: 
           newlist.append(i)
    print(newlist)

is_list_type(list1)
is_list_type(list2)
is_list_type(list3)

Solution
[1, 2]
[1, 0, 15]
[1, 2, 123]