Search code examples
pythonkeymax

why is max() printing the wrong amount?


list = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

print(len(max(list[0])))

Output: 7

why is the output 7 and not 8?

when i modify the print statement to:

print(len(max(list[0], key = len))) 

it works. I dont understand why. I hope someone can help me out.

thanks


Solution

  • By default, the max function returns the string with the highest value, ordered alphabetically. Which is "oranges", whose length is 8.

    When you provide the key as a second parameter, it compares strings by their length and not alphabetically.