0

I tried to find the max value in list .

Why does max(['66','9','44']) return 9? the max value need to be 66

2
  • 1
    it's comparing them as strings Commented Jan 11, 2021 at 19:42
  • max(map(int, ['66', '9', '44'])) Commented Jan 11, 2021 at 19:43

2 Answers 2

2

Use the key argument for max:

>>> max(['66','9','44'], key=int)
'66'

Reason being when comparing strings it compares each element in the string one by one and 9 is the highest first character.

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

Comments

1

Currently the numbers in your list are strings, and because of it max is returning lexicographical highest value. You can type-cast the numbers to int in order to get highest numeric value:

>>> max(map(int, ['66','9','44']))
66

Or, as mentioned in Jab's answer, you can use key param in the max function to change the value on which you need to perform sorting without changing the actual values in the list. For example:

>>> max(['66','9','44'], key=int)
'66'  # Value '66' is still preserved as string

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.