I have to find the max element in a list while filtering out all of the items inside of it that aren’t an integer or a float. So far I have this code and it seems to work except when giving the list [1, ]
. I get an error saying that the list is empty and I can’t find the max element.
def max_args(lst): if len(lst) == 0: return None for item in lst: if type(item) != [int or float]: lst.remove(item) return max(lst)
Advertisement
Answer
You can’t check type like that. You need to check using isinstance
. Also, you can’t do a for loop and do lst.remove(item)
the counter will get messed up.
I recommend you do a simple program to test it out. Here’s an example for you.
x = [2,'c',4.0,{'d':5},[6,7],8,(9,10)] print (x) for i,val in enumerate (x): print ('value at position : ',i, 'is : ', val) if not (isinstance(val,int)): x.remove(val)
The above code is supposed to iterate through each element of list x
. However, as you can see, it skips 4.0
and [6,7]
. The reason, you removed x[1]
and it resulted in 4.0
getting assigned to position x[1]
. Similarly for [6,7]
It moved one position to the left but your for loop iteration couldn’t catch it.
The output of the above code will be:
[2, 'c', 4.0, {'d': 5}, [6, 7], 8, (9, 10)] value at position : 0 is : 2 value at position : 1 is : c value at position : 2 is : {'d': 5} value at position : 3 is : 8 value at position : 4 is : (9, 10)
Instead, your code should be as follows:
def max_args(lst): print (lst) i = 0 while i < len(lst): if not (isinstance(lst[i], (int,float))): lst.pop(i) else: i +=1 if len(lst) == 0: return None else: return max(lst) x = max_args([1,'a',3,'b',5.0]) print (x) x = max_args([2,'c',4.0,{'d':5},[6,7],8,(9,10)]) print (x) x = max_args(['a']) print (x) x = max_args([7]) print (x) x = max_args([1,]) print (x) x = max_args([1,2,3,4,5,6]) print (x)
The output will be as follows:
[1, 'a', 3, 'b', 5.0] 5.0 [2, 'c', 4.0, {'d': 5}, [6, 7], 8, (9, 10)] 8 ['a'] None [7] 7 [1] 1 [1, 2, 3, 4, 5, 6] 6