1

'in' keyword in python - identity or equality?

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 delta):

>>> l = ['a', 'b', 'delta']
>>> if 'delta' in l:
...   print('K')
... 
K
>>> if l[2] is 'delta':
...   print('K')
... 
K
>>> if ('delt' + 'a') in l:
...   print('K')
... 
K
>>> if ('delt' + 'a') is l[2]:
...   print('K')
... 
K

Submitted September 11th 2021 by Admin

Answers
0

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 y is 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



Relevant Questions