0

In python, I know that it is permissible to write:

happy_bag = list()

if not (key in happy_bag):
    print(key, " ain't in da bag.")

But would it also be okay to write:

happy_bag = list()

if key not in happy_bag:
    print(key, " ain't in da bag.")

Also, the following is legal:

if key in happy_bag:
    print("Congratulations! you have a ", key, " in your bag!")

But is it alright if we add the word "is"?

if key is in happy_bag:
    print("Congratulations! you have a ", key, " in your bag!")
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • 2
    If there just were some interactive Python interpreter around to check that. ;-) – MSeifert Sep 14 '17 at 00:47
  • Title and content got out of sync. It seems like you answered the title already but asking a new question instead. Just a question though: What, if it were possible, would you expect `is in` to do? – MSeifert Sep 14 '17 at 00:51
  • @MSeifert I expect they're trying to make it read closer to English. They're probably not intending the `is` to act at the actual operator. – Carcigenicate Sep 14 '17 at 00:59
  • No, that's not possible. You can't always get code to read perfectly. – Carcigenicate Sep 14 '17 at 00:59

1 Answers1

1

It is perfectly correct to write:

container = []
key = 1
if key not in container:
    print("Not found")

And it is even advised. From PEP 8: Programming conventions

Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.

regarding your second question is in is not a correct operator in python. The operator is is used to test reference identity:

a = []
b = []
c = a
assert(a == b) # good, the two lists compare equal as per list.__eq__
assert(a is b) # fails, the two names don't refer to the same object
assert(a is c) # good, c and a point to the same list
Flynsee
  • 596
  • 4
  • 17