sosick
sosick

Reputation: 632

How to skip/ignore string list element?

I'm doing exercises, and I have a problem in one of them.

I have a print the smallest, and the highest number in a list. When the program sees a string, it has to ignore it. I don't know how to do it.

def find_hi_lo(list):
    return(min(list), max(list))

a = find_hi_lo([10, 2, 3, 4, 6])
print(a)

(2, 10)

a = find_hi_lo([10, 2, 3, 'aaa', 4, 6])
print(a)

Gives the error:

TypeError: unorderable types: str() < int()

Can you help me?

Upvotes: 0

Views: 5760

Answers (3)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

You can filter out all the undesired elements first.

from numbers import Number

def find_hi_lo(list0):
    temp = list(filter(lambda x: isinstance(x, Number), list0))
    return(min(temp), max(temp))

Upvotes: 4

chepner
chepner

Reputation: 531778

Lists can contain values of arbitrary types, but they work best when you restrict them to values of the same type (or, at least, values supporting any protocol expected by the consumer). In this case, both min and max expect values that are comparable to each other. The easiest thing to do here is to filter the strings out before you pass the list to find_hi_lo. Ideally, you would do this by not adding strings to the list in the first place, but you can remove them on demand like so:

find_hi_lo([x for x in [10, 2, 3, 'aaa', 4, 6] if not isinstance(x, str)])

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117926

You can use a list comprehension to filter out the non-numeric values

def find_hi_lo(data):
    data = [i for i in data if isinstance(i, float) or isinstance(i, int)]
    return min(data), max(data)

>>> find_hi_lo([10, 2, 3, 'aaa', 4, 6])
(2, 10)

Upvotes: 3

Related Questions