Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 149 ยท Operators

Membership and Identity Operators

Use in and not in to search strings, lists, sets and dicts, and is and is not to check object identity. Learn the real difference between == and is in Python.

Two kinds of questions come up so often that Python gives them their own operators. The first is "does this collection contain that value?", answered by in and not in. The second is "are these two names pointing at the very same object?", answered by is and is not.

The membership operators are some of the most readable tools in Python. The identity operators are simpler still, but they're easy to misuse, so this lesson spends some time on the difference between == and is.

Membership: in and not in

x in collection returns True if collection contains x. not in is the opposite. They work with every built-in collection type, and the meaning adapts to the type:

Python in with different types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Key points to remember:

  • For strings, in searches for a substring anywhere inside, so "row" in "brown" is True. Like all string comparisons it's case-sensitive; use .lower() on both sides to ignore case.
  • For dictionaries, in checks keys. Use .values() or .items() to search the rest; see Dictionaries.
  • Write x not in items rather than not x in items. Both work, but the first reads like English, and PEP 8 recommends it.

Replacing long or-chains

Membership tests make conditions shorter and fix the x == "a" or "b" bug you saw in Comparison and Logical Operators:

Python Cleaner conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Change the Input box to tue or Funday and run it again. .title() turns tue into Tue so the match works. if, elif and else are covered next in if, elif and else.

Speed: sets beat lists

How fast in runs depends on the collection. A list or tuple is checked item by item, so a list with a million items may need a million comparisons. A set or dict uses a hash table and answers in roughly constant time, however large it is:

Python Lists vs sets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a handful of options, a tuple is fine. When you check membership many times against a big collection, convert it to a set first. You'll learn more in Sets.

Identity: is and is not

Every value in Python is an object living somewhere in memory. A variable is just a name pointing at an object, and several names can point at the same one. The built-in id() function returns a number that identifies an object for its lifetime.

a is b returns True when a and b point to the same object, which is the same as id(a) == id(b). is not is the opposite.

Python Same object or just equal?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

first and second are equal (same contents) but not identical (different objects). first and alias are identical, which is why appending through alias changes first too. This is the same effect you saw with += in Assignment Operators and the Walrus.

== vs is

The difference comes down to the question each operator asks:

  • == asks "do these two values look the same?" It compares contents and can be customized by a class.
  • is asks "are these one and the same object?" It can't be customized.

So when should you use is? Almost only for singletons, values that exist exactly once in a program: None, True, False, and special sentinel objects you create yourself. That's why the None lesson recommends if value is None:.

Python Use is for None, == for values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The MISSING = object() sentinel is a common pattern: because a fresh object() is unique, is MISSING can tell "the key isn't there" apart from "the key is there and holds None".

Don't use is to compare numbers or strings

Python sometimes reuses objects for small integers and short strings to save memory. That's an implementation detail, and it makes is appear to work for values, until it suddenly doesn't:

Python
a = 256
b = 256
a is b        # True in CPython, because small ints are cached

x = 10 ** 6
y = 10 ** 6
x is y        # False: two separate int objects
x == y        # True: this is the comparison you want

Since Python 3.8, comparing with is against a literal, as in if x is 5:, produces a SyntaxWarning that tells you to use ==. Treat that warning as a bug report.

Warning: Use == to compare numbers, strings, lists and other values. Use is only for None, True/False and your own sentinel objects.

Making your own classes support in

Membership isn't limited to built-in types. When Python evaluates x in obj, it first looks for a special method called __contains__ on the object. If there isn't one, it falls back to iterating over the object and comparing each item with ==. That's why in works with ranges, generators, file objects and many library types. Once you reach Special (Dunder) Methods, you'll be able to write a class such as a Playlist that answers "Song title" in playlist in whatever way makes sense for it.

Note that membership itself uses == (with an identity shortcut first), not is. So 1.0 in [1, 2, 3] is True, because 1.0 == 1.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given prices = {"tea": 3, "cake": 5}, what is 3 in prices?

    in on a dictionary checks keys. Use 3 in prices.values() to search the values.
  2. 2. What does "cat" in "concatenate" return?

    For strings, in looks for a substring anywhere in the text, and "cat" appears inside "concatenate".
  3. 3. After a = [1, 2] and b = [1, 2], which is true?

    The lists have equal contents but are two separate objects.
  4. 4. When is is the right comparison?

    None is a singleton, so identity is the precise check. Use == for comparing values.
  5. 5. Which collection answers x in collection fastest for a large number of items?

    Sets use hashing, so membership checks take about the same time no matter how many items they hold.

Summary

  • in and not in test membership: elements for lists and tuples, substrings for strings, keys for dictionaries.
  • Prefer x in ("a", "b") over long or chains, and x not in items over not x in items.
  • Membership in sets and dicts is fast; in lists and tuples it checks items one by one.
  • is and is not test identity: whether two names refer to the same object.
  • == compares values; is compares identity. Use is only for None, True/False and sentinels.
  • Never rely on is for numbers or strings; small-value caching is an implementation detail.

Next: Bitwise Operators and Precedence.