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

I have a list:

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

He gives:

Max value element : zara

Also explain how it performs comparisons in a list of strings and a list of numbers.

+7
source share
2 answers

This is a really good question, and the answer depends on whether you use python2.x or python3.x ... And what python implementation you use 1 .

See here for a description of how python compares different types. The link says almost everything you need to know, but as a brief summary:

  • comparing objects of the same type acts as you expected.
  • name python2.x python3.x( ).
  • , .

1 , , , , .

+7

"" , ( , , "" ):

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

→ ,

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

→ kzla, kz ka kw

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

→ Warwick

Python 3.7, :

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

:

Traceback ( ): "", 1, TypeError: '>' 'str' 'int'

, Python 3.7 .

-1

All Articles