Python Forum

Full Version: is vs in
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am doing testing for exactly the same as opposed to equivalent. this means using the is keyword for comparison. comparing 1 to True (for example) i want to be False. but i have cases in a new project where i need to test if a variable is (or is not) the same as any of a few values. the in keyword does not compare like is. it compares more like ==. is there a way to do an is-like comparison against a list (or tuple) of values? i tried this in the hope there was a way but that is not implemented.
if this is in that:
    print('yes')
else:
    print('no')
if this cannot be done, then that syntax is my suggested addition.
No way to redefine it that I'm aware of.

Quote:For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

Given that, I would just redo your test as the same comprehension, just without the equality test.

>>> item = 1
>>> mylist = [True]
>>> item in mylist
True
>>> any(x is item for x in mylist)
False
(Dec-20-2020, 03:00 AM)bowlofred Wrote: [ -> ]Given that, I would just redo your test as the same comprehension, just without the equality test.

the appears to be the solution.