In python is "key not in container" allowed, or must we write "not (key in container)?"

53 views Asked by At

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!")
1

There are 1 answers

0
Flynsee On

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