1

How do comparison operators work? I thought they could be used only to compare numeric values, 5 <= 8, etc. But in this code sets are compared:

str = 'The quick Brow Fox'
alphabet = string.ascii_lowercase
alphaset = set(alphabet)

b = alphaset <= set(str.lower()) # Does it automatically extract length of objects?

print(len(alphaset))  # 26
print(len(set(str.lower())))  # 19
print(b)

26
15
False

I thought that it is impossible to do. alphaset <= set(str.lower()), you know literally is, e. g. set() <= set(). Does an operator implicitly call len() on such objects to find some numeric values to compare?

How does it know that one sequence is bigger, less or equal etc. to another?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I've found a better duplicate. Maybe not optimal. it's about `frozenset`. very similar to `set` – Jean-François Fabre May 04 '18 at 12:35
  • I suspect you actually wanted `alphaset >= set(str.lower())` there. FWIW, `alphaset.issubset(s.lower())` is a little more efficient than `alphaset <= set(s.lower())` since the former doesn't need to convert its arg to a set. (BTW, please don't use `str` as a variable name. That shadows the built-in `str` type, which can lead to confusing error messages). – PM 2Ring May 04 '18 at 12:41

2 Answers2

0

From the Python manual:

issubset(other)
set <= other

       Test whether every element in the set is in other.

There are a variety of magic methods you can implement if you want to overload operators for your own classes. When you call a < b Python defers to a.__le__(b) if such a method exists.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Python supports operator overloading, which means that any class can implement methods that provide access to the standard operators.

For full documentation of what you can do in Python, including which methods a class can implement to support different operators, check out the Python data model.

For a description of how a built-in type like set implements its operators, see that type's documentation. For example, documentation for the set type.

James Bennett
  • 10,903
  • 4
  • 35
  • 24