inExpert Examples

Membership test operator; also used in for loops to iterate over items

in bytecode: CONTAINS_OP

How membership testing compiles.

python
import dis

def test_in(x, y):
    return x in y

def test_not_in(x, y):
    return x not in y

print("x in y:")
dis.dis(test_in)
print("\nx not in y:")
dis.dis(test_not_in)

# CONTAINS_OP 0 = 'in', CONTAINS_OP 1 = 'not in'
# Internally calls PySequence_Contains which:
# 1. Tries __contains__
# 2. Falls back to iteration

# For loop 'in' uses a different opcode (GET_ITER/FOR_ITER)
def for_in():
    for x in [1, 2, 3]:
        pass

print("\nfor x in y (different opcode):")
dis.dis(for_in)

'in' for membership compiles to CONTAINS_OP, while 'in' in for loops compiles to GET_ITER + FOR_ITER. They look the same in source but are completely different operations.

Want to try these examples interactively?

Open Expert Playground