4

min() function should return the smallest of the numbers given. Then why

min({0},{1})

returns {0}, while

min({1},{0})

returns {1}?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Adam Ježek
  • 464
  • 5
  • 15
  • My question would be why don't dictionaries behave similarly?.. – Ma0 Jun 08 '17 at 12:19
  • @Ev.Kounis In Python 3 `dict` is an unorderably type, but in Python 2, they are compared https://stackoverflow.com/questions/3484293/is-there-a-description-of-how-cmp-works-for-dict-objects-in-python-2 – Chris_Rands Jun 08 '17 at 12:21

3 Answers3

7

In python sets are compared based on whether or not one is a subset of the other.

None is a subset of the other, so < gives False in all cases, so the first one is returned.

So {1}<{0} gives False just like {2}<{1} gives False and {2}<{3,4,5} gives False. However {1,2}<{1,3,2} gives True. This means there is no total order defined on sets.

Bernhard
  • 2,084
  • 2
  • 20
  • 33
  • 3
    this is inncorrect `min({1,3,4,5},{0,2})` returns `{1, 3, 4, 5}`, which is of the smaller size – harshil9968 Jun 08 '17 at 12:21
  • My original answer was indeed incorrect. I edited the answer to give the correct answer: Set compare based on `is_subset` relation. – Bernhard Jun 08 '17 at 12:22
5

The comparison operators for sets check for "subset" not for numerical comparisons:

set < other

Test whether the set is a proper subset of other, that is, set <= other and set != other.

And both your sets are disjoint so {0} < {1} == False and {1} < {0} == False so it will always return the "first" set you put into min.

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352
4

Because these are sets, not numbers.

Moreover, it should return {1}, not 1, as you can see here:

>>> min({0},{1})
set([0])
>>> min({1},{0})
set([1])

That means that it will return the set, not the number.

gsamaras
  • 71,951
  • 46
  • 188
  • 305