0

My question is purely educationalal for myself but is not homework (heck I'm not even in school but this question seems like a prime target for those suggesting it is homework). Is there a difference between:

if 'value' not in data: ...

...and...

if not 'value' in data: ...

Based on my brief test, on the surface they seem to function the same. Is there a scenario where they yield different, opposing results? Is one faster than the other? Is one "more correct" than the other?

Reading and writing code, my preference is for the first version.

Thanks.

user1801810
  • 614
  • 1
  • 11
  • 29
  • The call to `data.keys` is redundant here. Your code would work fine (better) as: `if 'value' not in data:`. –  Mar 18 '14 at 15:57
  • In fact, if you're using Python 2, then using `data.keys()` will be much slower for large dictionaries, because first it constructs a list of the keys and then it has to search them one by one. – DSM Mar 18 '14 at 15:58
  • Ok, so I changed where the check is being done but I think that has no bearing on the question since both statements were the same to begin with except for the location of 'not'. – user1801810 Mar 18 '14 at 16:03
  • Aha, the linked question on the same subject helps. Thanks. – user1801810 Mar 18 '14 at 16:05
  • 1
    @user1801810: that's why these were comments, and both of us agreed that this was a duplicate of the other one. :^) – DSM Mar 18 '14 at 16:05

0 Answers0