PythonOperatorsBitwise & Identity Operators

Bitwise & Identity Operators

This page covers two distinct but important categories of operators: bitwise operators, which perform low-level manipulation on integers, and identity operators, which compare the memory locations of objects.

1. Bitwise Operators

Bitwise operators treat integers as if they were sequences of binary digits (bits). They are used in specialized domains like low-level device control, data compression, and encryption.

To understand these, it helps to think in binary. For example, the number 5 is 0b101 and 3 is 0b011.

Bitwise AND &

Sets each bit to 1 only if both corresponding bits in the operands are 1.

Pyground

Calculate the bitwise AND of 5 (0b101) and 3 (0b011).

Expected Output:

5 & 3 = 1

Output:

Use Case: Flags and Masks

A common use for bitwise operators is to manage a set of boolean flags within a single integer.

Pyground

Manage file permissions (Read, Write, Execute) using bitwise flags.

Expected Output:

User permissions value: 5
Can user write? False
Can user read? True

Output:

2. Identity Operators (is and is not)

Identity operators compare the memory location of two objects, not their values.

  • a is b: Returns True if a and b point to the exact same object in memory.
  • a is not b: Returns True if a and b point to different objects in memory.

is vs. == (Identity vs. Equality)

This is a crucial distinction:

  • == checks if the values of two objects are equal.
  • is checks if two variables refer to the same object.

Pyground

Create two different list objects that have the same content and compare them using both `==` and `is`.

Expected Output:

list_a == list_b: True
list_a is list_b: False
list_a == list_c: True
list_a is list_c: True

Output:

When to Use is

The primary use case for identity operators is to compare a variable against a singleton object—an object for which there is only ever one instance. The most common singletons are None, True, and False.

Pyground

Check if a variable is None using the recommended `is` operator.

Expected Output:

The variable has no value.

Output:

🚨

Do not use is to compare literal values like numbers or strings. Python internally caches (interns) small integers and short strings, which can make is seem to work by coincidence. This behavior is an implementation detail and should not be relied upon. Always use == for value equality.