J. Smith
J. Smith

Reputation: 53

how do I filter on integers in a list containing different data types in python

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

Answers (3)

Boss
Boss

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

Kevin Mayo
Kevin Mayo

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

Alexanderbira
Alexanderbira

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

Related Questions