How does the max() function work on list of strings in python?

前端 未结 3 1511
攒了一身酷
攒了一身酷 2020-11-29 10:06

I have a list:

list1 = [123, \'xyz\', \'zara\', \'abc\']
print \"Max value element : \", max(list1);

It gives:

Max value e         


        
3条回答
  •  难免孤独
    2020-11-29 10:48

    It "orders" the words alphabetically and returns the one that is at the bottom of the alphabetic list (for the record, it doesn't not change the order of the items in your list, that's why I wrote "orders" inside quotation marks):

    list1 = ["kyle", "darius"]
    max(list1) 
    

    --> returns kyle because k is after d

    list2 = ["kaula", "kzla", "kayla", "kwala"]
    max(list2) 
    

    --> returns kzla because kz is alphabetically ordered after ka and kw

    list3 = ["kyle", "darius", "janna", "set", "annie", "warwick", "bauuuuuu"]
    max(list3)
    

    --> returns warwick

    I'm using python 3.7, and when I try to mix strings with numbers:

    list4 = [13341412, "zara", "jane", "kada"]
    max(list4)
    

    I get an error:

    Traceback (most recent call last): File "", line 1, in TypeError: '>' not supported between instances of 'str' and 'int'

    At least in python 3.7, you cannot mix integers with strings.

提交回复
热议问题