0

I was reviewing some code today and saw what I figured was a typo:

if foo <> bar:
    # do stuff

However, I'm surprised to see that Python2 appears to treat <> as valid:

% python -c 'print 1<>2'
True

Additionally, I can't discern what causes <> to return True vs False:

In [16]: 1 <> 2
Out[16]: True

In [17]: 2 <> 1
Out[17]: True

In [18]: 1 <> None
Out[18]: True

In [19]: 1 <> "foo"
Out[19]: True

In [20]: None <> 1
Out[20]: True

In [21]: None <> None
Out[21]: False

In [22]: False <> 1
Out[22]: True

One of my guesses was that Python was using both the < and > operators and I was falling victim to some boolean casting shenanigans, but that doesn't appear to be the case as < > isn't valid and neither is ><:

In [29]: 1 >< 2
  File "<ipython-input-29-0e35e3b94016>", line 1
    1 >< 2
       ^
SyntaxError: invalid syntax

In [30]: 1 < > 2
  File "<ipython-input-30-8f2ba3fa3c6c>", line 1
    1 < > 2
        ^
SyntaxError: invalid syntax

Finally, Python 3 chokes on this "operator" (or whatever it should be called):

% python3 -c 'print(1<>2)'
  File "<string>", line 1
    print(1<>2)
            ^
SyntaxError: invalid syntax

So, what gives? What is <> doing? What is it? Why is it invalid in Python 3?

Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
  • @minitoto I mean, I asked this question specifically because I couldn't figure out how to google what the "<>" operator was, so I wouldn't consider that question a duplicate in that I attempted to find it and my searches failed me. But I suppose that answer does answer my question, now that I know the answer. Obviously I am familiar with the `!=` operator – Nolen Royalty Jan 27 '16 at 03:55
  • no offense but i think it's the problem of the mass, some people just can't google or fail to and ask duplicate questions which are already have good answers – midori Jan 27 '16 at 03:57
  • I'm not sure it's possible to Google a symbol like that. – Paul Jan 27 '16 at 04:07
  • yeah, I didn't really have any luck with google or SO's search when it came to `<>`. In retrospect I should have just ctrl-f'd on python operator docs. – Nolen Royalty Jan 27 '16 at 04:28
  • 2
    Try [**SymbolHound search**](http://symbolhound.com/?q=%3C%3E+python) for stuff like this. – Stefan Pochmann Jan 27 '16 at 04:39

1 Answers1

4

That's a legacy way of writing !=. Don't use it in new code. As you've already seen, it was removed in python3.x (probably because "There should be one-- and preferably only one --obvious way to do it." and because nobody used that operator :-).

The documentation can be found here:

The forms <> and != are equivalent; for consistency with C, != is preferred; where != is mentioned below <> is also accepted. The <> spelling is considered obsolescent.

mgilson
  • 300,191
  • 65
  • 633
  • 696