Python Membership Operators

With the Python membership operators, we can check if an item exists in another item like a string, list, tuple, or dictionary. These operators are one of the Python operator types.

There are two operators:

  • IN: Returns true if the item exists, otherwise returns false.
  • NOT IN: Returns true if the item does not exist, otherwise returns false.

Let’s try some examples.

IN Operator

The IN operator returns True if the item exists. For example, we can check if a string exists in a string:

>>> "down" in "Line protocol on Interface Loopback0, changed state to down"

Will show this output:

True

Or if a string exists in a list:

>>> "SW1" in ["SW1", "SW2", "SW3"]

Will show this output:

True

Or whether a number exists in a list:

>>> 403 in [400, 401, 402, 403]

Will show this output:

True

Or if a certain key exists in a dictionary:

Unlock This Lesson for Free - No Credit Card Needed!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2363 Sign Ups in the last 30 days

Ask a question or start a discussion by visiting our Community Forum