user1050619
user1050619

Reputation: 20856

Python list max function when a list item is present

I was trying to find a max of element in a list but noticed something strange when the list contains another list item.

code.py

a=[[1,2],3,4]
max(a)
[1,2]

how does the max function works in the above works?

How does the list element is assumed as the max element...

Thanks for your help.

Upvotes: 2

Views: 162

Answers (1)

phihag
phihag

Reputation: 287825

In Python 2, comparisons between incomparable types return a meaningless (but consistent) result:

>>> [1,2] > 3
True

max uses these comparisons to find the largest element, which in this case happens to be the list.

This has been fixed in Python 3, where you'd get:

>>> max([1,2], 3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() > list()

Upvotes: 4

Related Questions