I am aware that
is tests for identity and not equality of objects (eg. strings) in python. However I am curios whether
in checks for equality or identity when used to check if an item is in a list / dict ?
I am unable to test this reliably as my interpreter seems to be be
interning strings automatically at will (as you can see below even the
is test passes implying only one copy of string was created in memory for all representations of
>>> l = ['a', 'b', 'delta'] >>> if 'delta' in l: ... print('K') ... K >>> if l is 'delta': ... print('K') ... K >>> if ('delt' + 'a') in l: ... print('K') ... K >>> if ('delt' + 'a') is l: ... print('K') ... K
According to the python documentation, for built-in container types,
in tests for both identity and equality. This is the relevant line:
For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression
x in yis equivalent to
any(x is e or x == e for e in y).
Edit: updated the answer per juanpa.arrivillaga's comment, for non built-in container types, the behavior is implementation dependent.
Admin | 1 month ago