When to use `<>` and `!=` operators?

后端 未结 2 1392
有刺的猬
有刺的猬 2021-01-24 01:11

Couldn\'t find much on this. Trying to compare 2 values, but they can\'t be equal. In my case, they can be (and often are) either greater than or less than.

Should I use

相关标签:
2条回答
  • 2021-01-24 01:59

    Just stick to !=.

    <> is outdated! Please check recent python reference manual.

    0 讨论(0)
  • 2021-01-24 02:14

    Quoting from Python language reference,

    The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent.

    So, they both are one and the same, but != is preferred over <>.

    I tried disassembling the code in Python 2.7.8

    from dis import dis
    form_1 = compile("'Python' <> 'Python'", "string", 'exec')
    form_2 = compile("'Python' != 'Python'", "string", 'exec')
    dis(form_1)
    dis(form_2)
    

    And got the following

      1           0 LOAD_CONST               0 ('Python')
                  3 LOAD_CONST               0 ('Python')
                  6 COMPARE_OP               3 (!=)
                  9 POP_TOP
                 10 LOAD_CONST               1 (None)
                 13 RETURN_VALUE
    
      1           0 LOAD_CONST               0 ('Python')
                  3 LOAD_CONST               0 ('Python')
                  6 COMPARE_OP               3 (!=)
                  9 POP_TOP
                 10 LOAD_CONST               1 (None)
                 13 RETURN_VALUE
    

    Both <> and != are generating the same byte code

                  6 COMPARE_OP               3 (!=)
    

    So they both are one and the same.

    Note:

    <> is removed in Python 3.x, as per the Python 3 Language Reference.

    Quoting official documentation,

    != can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=.

    Conclusion

    Since <> is removed in 3.x, and as per the documentation, != is the preferred way, better don't use <> at all.

    0 讨论(0)
提交回复
热议问题