Skip to content
Advertisement

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

I have a list:

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

It gives:

Max value element : zara

Please also explain how it perform comparison on list of strings and list of numbers.

Advertisement

Answer

This is actually a good question and the answer varies depending on whether you’re on python2.x or python3.x … And which python implementation you’re using1.

See here for a description of how python compares different types. The link says pretty much all that you need to know, but as a quick summary:

  • comparison of objects of the same type acts as you’d expect.
  • comparison of objects of different type are ordered by their type name on python2.x and raise an error on python3.x (Unless a custom comparison operator is defined.)
  • old style classes break all the rules but they shouldn’t be used anyway.

1Hopefully you can see by the amount of uncertainty there that this is not really well defined and so it’s a situation that you should try to avoid.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement