🎓 A1Learner
🔍

Python Identity & Membership Operators

A membership operator asks if a value is inside a string or a list. An identity operator asks if two names point to the very same object.

Is a letter inside a word?

The word in checks if the text holds that letter.

print("a" in "cat")
print("z" in "cat")

Check a list

The word in also works on the items of a list.

shopping = ["milk", "bread"]
print("milk" in shopping)
print("eggs" not in shopping)

Equal is not the same object

The lists hold the same items. They are still two separate lists.

first = [1, 2]
second = [1, 2]
print(first == second)
print(first is second)

One list, two names

Here second is set to first, so both names point to one list.

first = [1, 2]
second = first
print(first is second)

Check for None

None means no value yet. The safe check for it uses is.

player = None
print(player is None)
print(player is not None)

Example

shopping = ["milk", "bread", "eggs"]
other = ["milk", "bread", "eggs"]
print("Has milk:", "milk" in shopping)
print("Has cheese:", "cheese" in shopping)
print("Lists look equal:", shopping == other)
print("Lists are same object:", shopping is other)

Key points

  • Object: a single value or collection that Python stores and can point to.
  • Use in to ask if a value is inside a string or a list.
  • Use not in to ask if a value is missing.
  • Use == to compare values.
  • Use is to compare identity, which means the same object.
  • Identity: two names share an identity only if they point to one object.
  • Safest rule: use is and is not mainly to check for None.

In this example, shopping holds milk, bread, and eggs. Python finds milk in the list and gets True. It does not find cheese and gets False. The two lists hold the same items, so == is True, but is is False.

Note

Two lists can hold the same items and still be two lists.

So == can be True while is is False.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does "milk" in ["milk", "bread"] give?