Reputation: 53
I have a list containing both integers and strings.
old_list = ['Hello', 'fox', 13, 10, 22, 5]
I'd like to filter the list to remove values that are less than or equal to 10
new_list = ['Hello', 'fox', 13, 22]
I'm trying to do this using either a list comprehension or ideally a filter. My initial attempt at this is below:
def filter(input):
return [x for x in old_list if isinstance(x, int) and x <= 10
This results in an output of:
[13, 22]
Thanks for any guidance! I'm new to python and this is my first post, so apologies if there are issues with how I've made the submission.
Upvotes: 0
Views: 1449
Reputation: 22
If you are only trying to remove the integers that are equal or less than 10 and not modify the strings:
old_list = ['Hello', 'fox', 13, 10, 22, 5]
new_list = [x for x in old_list if type(x) == str or x > 10]
print(new_list)
If you only want integers that are more than 10 and nothing else:
old_list = ['Hello', 'fox', 13, 10, 22, 5]
new_list = [x for x in old_list if type(x) == int and x > 10]
print(new_list)
Upvotes: 0
Reputation: 1159
Python has a builtln function called filter()
. It is not recommend you redefine it.Also,You could use it directly:
old_list = ['Hello', 'fox', 13, 10, 22, 5]
new_list = list(filter(lambda x: isinstance(x, str) or x > 10,old_list)))
# ['Hello', 'fox', 13, 22]
Upvotes: 0
Reputation: 444
This adds all the values from the input that are not integers smaller than 10 to the result:
def filter(input):
return [x for x in old_list if not (isinstance(x, int) and x <= 10)]
Upvotes: 2