0

If the list is :

list = ["3" ,"5" ,"dog" , "1"]

and I want to add the max and min numbers within the list how do you do it? I was thinking I would do a loop and compare each of the numbers as iterating though, but as you can see there's a string in the list.

How do you compare the ints to find the max and min without getting an error because of the string?

1
  • Those are all strings. Do you mean "the numeric value of the strings which could be converted to numbers?" If so, how strict is the restriction supposed to be? Commented Feb 2, 2021 at 5:19

4 Answers 4

2

Try this:

test_list = ["3" ,"5" ,"dog" , "1"]

max([x for x in test_list if x.isnumeric()])
# 5

the list comprehension inside max basically filters only the numeric elements.

EDIT:

If you need to catch decimals and negative numbers as well:

original_list = ["3" ,"-5." ,"dog" , "-1"]
numerics_only_list = [x for x in a if x.lstrip('-').replace('.', '', 1).isnumeric()]
max(numerics_only_list)
# 5.
min(b)
# -1

Basically, I am removing the leftmost - sign and ONLY 1 decimal point.

Sign up to request clarification or add additional context in comments.

1 Comment

I just realized, this will only work for positive numbers and decimals. "-5" will fail the isnumeric test and so will "1.0".
1

You can do a loop like you planned. You just have to catch the exceptions where there is no int value for the item:

list = ["3", "5", "dog", "1"]
cleaned =[]
for item in list:
    try:
        if int(item):
            cleaned.append(int(item))
    except(Exception):
        pass
result = max(cleaned) + min(cleaned)

print(result)
#prints 6

Comments

0

Um not sure if this helps but have you tried doing it this way?

list = ["3" ,"5" ,"dog" , "1"]
mininum_number = min(list)
print(mininum_number)
maximum_number = max(list)
print(maximum_number)

The min() function will find the minimum Unfortunately the max() function will select dog but it didnt give me an error

Comments

0

You can use List comprehension to filter the numeric items then it is easy to find max and min:

test_list = ["3" ,"5" ,"dog" , "1"]
nums = [item for item in test_list if item.isnumeric()]
print(max(nums))
# 5
print(min(nums))
# 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.