1

which way of checking item in list is correct?

>>> lst1 = ['A', 'B']
>>> if 'C' not in lst1: print 'Hi'
...
Hi

or

>>> if not 'C' in lst1: print 'Hi'
...
Hi

to me the first one looks correct but still in doubt ? not sure if this has been asked by someone on SO before if so please link

Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197
  • 5
    Either one works. Subjectively I prefer `if 'c' not in lst` because I find it more human readable – Adam Smith Feb 06 '15 at 05:35
  • possible duplicate of [Python \`if x is not None\` or \`if not x is None\`?](http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none) – Andy Feb 06 '15 at 05:38

2 Answers2

1

The latter works, but some would consider it poor form or "less Pythonic". The former is more readable, and Python prides itself on being a highly readable language.

Readability counts.

— Tim Peters, The Zen of Python

fletom
  • 1,998
  • 13
  • 17
0

They are equally correct for this case.

In the more general case such as when calling a function which returns a boolean, the not must go in front, so if that is easier for you to remember, you could stick with that to be consistent.

merlin2011
  • 71,677
  • 44
  • 195
  • 329