0

Python code:

print(max(['2020','4','70','5']))

I am getting the output as 70

I want to understand how max() works on strings.

Can anyone explain?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

-1

max() can be used in 2 ways

  1. Finding the largest item in an iterable
max(iterable, *iterables, key, default)
  1. Getting the largest number in a list
number = [3, 2, 8, 5, 10, 6]
largest_number = max(number);

I think that what you want is this last one. If you also added a

print(largest_number)

It would throw you the output of 10.

dvnt
  • 196
  • 4
  • 15
  • 1
    Are you implying that `list` is **not** `iterable`? – PM 77-1 Jun 27 '20 at 17:17
  • No but in this case I think in this specific case he should even change `['2020','4','70','5']` to `[2020,4,70,5]` since he seems to be trying to print the largest number and doing so will fix the "error" he's getting – dvnt Jun 27 '20 at 17:19
  • 1
    OPs problem is that she does not understand the difference between numeric value and its character representation and you answer does not help. – PM 77-1 Jun 27 '20 at 17:21
  • Seems clear to me but alright. It's literally there that for numbers, your best choice would be going with what I pointed as "2." – dvnt Jun 27 '20 at 17:24
  • https://stackoverflow.com/questions/20463204/how-does-the-max-function-work-on-list-of-strings-in-python – AMC Jun 27 '20 at 20:39
  • _I think that what you want is this last one._ You should make it clear that the difference is in the values (and their type), not how you use the function. It's a bit confusing. – AMC Jun 27 '20 at 20:40
-1

if you provide max() a string, it returns the highest alphabetical character in a string. So it will order based on alphabetical order descending.

As explained here https://www.geeksforgeeks.org/python-string-max/#:~:text=os._exit()-,Python%20String%20%7C%20max(),alphabetical%20character%20in%20a%20string.&text=Return%20value%3A,highest%20character%20in%20the%20string.

  • https://stackoverflow.com/questions/20463204/how-does-the-max-function-work-on-list-of-strings-in-python – AMC Jun 27 '20 at 20:39