1

Probably seems like an incredibly trivial question, but I'm curious, and given:

foo = {1: 'one', 2: 'two'}

Is there a reason to prefer either one of the following two approaches?

if not 3 in foo:
    print 'bar'


if 3 not in foo:
    print 'bar'
HorseloverFat
  • 3,290
  • 5
  • 22
  • 32
  • seems this question has been asked so many times. should I delete it? – HorseloverFat Oct 29 '13 at 11:09
  • 2
    ["Readability counts"](http://www.python.org/dev/peps/pep-0020/): I would prefer option 2 over 1 for its readability. Syntactic they are the same. – RickyA Oct 29 '13 at 11:09
  • @HorseloverFat: Just VTC as a duplicate so that there are more signposts to the original questions. Your question will remain on the site to point searches the right way. – Martijn Pieters Oct 29 '13 at 11:10
  • @HorseloverFat If you didn’t get any of the other questions suggested while typing your question, then maybe the search terms were not that good. As such it’s okay, if you leave the question and get it closed. – poke Oct 29 '13 at 11:11

1 Answers1

2

They are functionally equivalent, though the latter is more pythonic.

  • 1
    Why is the latter more Pythonic? Any particular reason? – HorseloverFat Oct 29 '13 at 11:06
  • 1
    I think because it resembles English better. `not in` is also more common. –  Oct 29 '13 at 11:08
  • 2
    @HorseloverFat "Pythonic" is just a synonym for "idiomatic in the Python community" although it's often used to mean "preferable because the meaning is clearer". In this case it is difficult to misread `3 not in foo` as anything other than `3 (not in) foo` whereas you might misread `not 3 in foo` as `(not 3) in foo` rather than `not (3 in foo)`. – Chris Taylor Oct 29 '13 at 11:08
  • The latter is what the Python compiler optimizes for as it is just *one* bytecode instruction vs. two for the other option. – Martijn Pieters Oct 29 '13 at 11:15