I. Overview of Bitwise and Membership Operations
Python provides a variety of operators for working with the binary bits of integers and for determining whether an element belongs to a given container.
Among them, bitwise operations act directly on the binary representation of integers and are commonly used for permission flags, state management, mask operations, low-level data processing, and similar scenarios.
Membership operations are used to determine whether an element exists in a specified object, and are commonly used for string searching, list lookup, set testing, and dictionary key checks.
The core differences between the two kinds of operations:
| Comparison Dimension | Bitwise Operations | Membership Operations |
|---|---|---|
| Core goal | Operate on binary bits | Determine whether an element exists |
| Main operators | &, |, ^, ~, <<, >> |
in, not in |
| Main operands | Integers and custom objects that support the relevant operations | Containers, strings, iterables, etc. |
| Return result | Usually an integer or a custom operation result | bool |
| Typical scenarios | Permissions, flag bits, masks, bit fields | Searching, filtering, validation, conditional checks |
II. Fundamentals of Python Bitwise Operations
1. What Are Bitwise Operations
Computers represent integers using binary, and each binary bit can only be 0 or 1.
For example:
a = 10
b = 6
print(bin(a)) # 0b1010
print(bin(b)) # 0b110
The corresponding binary representations:
10 = 1010
6 = 0110
Bitwise operations apply their rules bit by bit on the binary digits, rather than performing ordinary arithmetic directly on two integers.
Python integers have arbitrary precision, and bitwise operations on negative numbers follow infinite-width two's-complement semantics. Therefore, you cannot simply assume that a negative number occupies a fixed 32 or 64 bits.
2. Overview of Bitwise Operators
The common bitwise operators in Python include:
| Operator | Name | Effect |
|---|---|---|
& |
Bitwise AND | The result is 1 only when both bits are 1 |
| |
Bitwise OR | The result is 1 when at least one of the two bits is 1 |
^ |
Bitwise XOR | The result is 1 when the two bits differ |
~ |
Bitwise NOT | Inverts the binary bits of an integer |
<< |
Left Shift | Shifts the binary bits to the left |
>> |
Right Shift | Shifts the binary bits to the right |
All of these operators can be applied directly to Python integers.
III. Bitwise AND Operation (&)
1. Basic Principle
Bitwise AND requires that both corresponding binary bits be 1 for the result to be 1.
Truth table:
| A | B | A & B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
For example:
a = 10 # 1010
b = 6 # 0110
result = a & b
print(result) # 2
print(bin(result)) # 0b10
Bit-by-bit calculation:
1010
& 0110
------
0010
Therefore:
10 & 6 == 2
2. Checking Whether a Certain Bit Is 1
One of the most common uses of bitwise AND is to determine whether a particular binary bit of an integer is set.
For example, to check whether bit 2 of an integer is 1:
number = 10
mask = 1 << 2
if number & mask:
print("第 2 位为 1")
else:
print("第 2 位为 0")
Here the numbering starts from the least significant bit, beginning at 0:
Decimal 10:
bit index: 3 2 1 0
binary: 1 0 1 0
1 << 2 yields the binary mask 0100.
Perform the bitwise AND:
1010
& 0100
------
0000
The result is 0, which means bit 2 is not set.
3. Extracting specified bits
Suppose an integer holds multiple status bits; a mask can be used to extract a subset of them.
value = 0b11010110
mask = 0b00001111
result = value & mask
print(bin(result)) # 0b110
print(result) # 6
The lower four bits of the mask are 1 and the remaining positions are 0, so the lower four bits of the original integer are extracted.
4. Common applications
- Checking permission flags.
- Determining whether a given state is enabled.
- Extracting protocol fields.
- Checking the parity of an integer.
Parity can be determined with the least significant bit:
number = 15
if number & 1:
print("奇数")
else:
print("偶数")
IV. Bitwise OR (|)
1. Basic principle
In a bitwise OR, as long as at least one of the two corresponding bits is 1, the result is 1.
Truth table:
| A | B | A | B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
For example:
a = 10 # 1010
b = 6 # 0110
result = a | b
print(result) # 14
print(bin(result)) # 0b1110
Bit by bit:
1010
| 0110
------
1110
2. Setting specified bits
Bitwise OR can set a specified bit to 1 while leaving the other bits in their original state.
number = 0b1000
mask = 0b0010
result = number | mask
print(bin(result)) # 0b1010
Whether the target bit was originally 0 or 1, it becomes 1 after the bitwise OR.
3. Combining multiple flag bits
Suppose a system has several permissions:
READ = 1 << 0
WRITE = 1 << 1
EXECUTE = 1 << 2
permissions = READ | WRITE
print(bin(permissions)) # 0b11
This means the current object holds both read and write permissions.
If execute permission needs to be added:
permissions |= EXECUTE
print(bin(permissions)) # 0b111
|= is the bitwise OR assignment operator, and its effect is equivalent to:
permissions = permissions | EXECUTE
V. Bitwise XOR (^)
1. Basic principle
In XOR, the result is 1 only when the two corresponding bits differ.
Truth table:
| A | B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
For example:
a = 10 # 1010
b = 6 # 0110
result = a ^ b
print(result) # 12
print(bin(result)) # 0b1100
Bit by bit:
1010
^ 0110
------
1100
2. Flipping specified bits
XORing with a mask whose bits are 1 flips the corresponding positions.
number = 0b1010
mask = 0b0010
result = number ^ mask
print(bin(result)) # 0b1000
If the target bit was originally 1, it becomes 0; if it was originally 0, it becomes 1.
3. Common properties of XOR
XOR has the following properties:
| Property | Expression |
|---|---|
| XOR with 0 | a ^ 0 == a |
| XOR with itself | a ^ a == 0 |
| Commutativity | a ^ b == b ^ a |
| Associativity | (a ^ b) ^ c == a ^ (b ^ c) |
| Flip twice in succession | (a ^ b) ^ b == a |
For example:
number = 12
mask = 5
result = number ^ mask
restored = result ^ mask
print(number) # 12
print(restored) # 12
XOR can be used for simple bit flipping, checksum calculations, and certain algorithmic tricks, but it should not be treated as a modern encryption algorithm.
4. Swapping Variables with XOR
Traditional algorithms once used XOR to swap two integers:
a = 10
b = 20
a ^= b
b ^= a
a ^= b
print(a, b) # 20 10
However, Python more strongly recommends using multiple assignment directly:
a, b = b, a
It is clearer and more in line with Python programming conventions.
6. Bitwise NOT Operation (~)
1. Basic Principles
Bitwise NOT changes binary bits from 0 to 1 and from 1 to 0.
For Python integers, bitwise NOT satisfies:
~n == -(n + 1)
For example:
number = 5
print(~number) # -6
Why isn't it simply 101 becoming 010, that is, decimal 2?
Because Python uses infinite-width two's complement semantics for negative numbers. Bitwise NOT can be understood as:
~5 = -(5 + 1) = -6
2. Bitwise NOT of Negative Numbers
print(~0) # -1
print(~1) # -2
print(~5) # -6
print(~10) # -11
print(~-1) # 0
When understanding bitwise NOT in Python, the most important thing to remember is:
~n == -n - 1
Do not directly apply the NOT result for fixed 8-bit, 16-bit, or 32-bit integers.
3. Simulating NOT in Fixed-Width Scenarios
If a use case requires simulating an 8-bit unsigned integer, you can use a mask to constrain the result:
number = 0b10101010
mask = 0b11111111
result = ~number & mask
print(bin(result)) # 0b1010101
print(format(result, "08b")) # 01010101
& mask keeps the lower 8 bits, thereby producing the NOT result under a fixed width.
7. Left Shift Operation (<<)
1. Basic Principles
The left shift operation moves an integer's binary bits to the left by a specified number of positions, filling the vacated low-order bits on the right with 0.
For example:
number = 5
result = number << 2
print(result) # 20
print(bin(result)) # 0b10100
Calculation process:
Original: 00000101
Left shift: 00010100
Mathematically, for non-negative integers:
n << k == n * (2 ** k)
where k is a non-negative integer.
2. Creating Masks with Left Shift
Left shift is often used to create masks for specific bit positions:
bit_0 = 1 << 0
bit_1 = 1 << 1
bit_2 = 1 << 2
bit_3 = 1 << 3
print(bin(bit_0)) # 0b1
print(bin(bit_1)) # 0b10
print(bin(bit_2)) # 0b100
print(bin(bit_3)) # 0b1000
This approach is easier to maintain than manually writing out binary numbers.
3. Restrictions on Shift Counts
The shift count must be a non-negative integer:
print(5 << 2) # 20
# The following operation will raise ValueError
# print(5 << -1)
Python integers support arbitrary precision, so left shifting generally causes the integer to keep growing, but it also increases memory consumption.
8. Right Shift Operation (>>)
1. Basic Principles
The right-shift operation shifts the binary bits of an integer to the right by a specified number of positions.
For Python integers, right shift uses arithmetic right-shift semantics: the high bits are extended using the sign bit.
For example:
number = 20
result = number >> 2
print(result) # 5
print(bin(result)) # 0b101
Calculation process:
Original: 00010100
Right shift: 00000101
For non-negative integers:
n >> k == n // (2 ** k)
Here, // is integer division that rounds toward negative infinity.
2. Right shift of negative numbers
Special care is needed when right-shifting negative numbers:
print(-8 >> 1) # -4
print(-9 >> 1) # -5
The result of -9 >> 1 is -5, not -4.
This is because:
-9 // 2 == -5
The right-shift operation is consistent with Python's rounding-toward-negative-infinity rule.
3. Differences between left shift and right shift
| Aspect | Left shift << |
Right shift >> |
|---|---|---|
| Shift direction | Left | Right |
| Main effect | Increases the value | Decreases the value |
| Vacated-bit handling | Low bits filled with 0 | Sign extension of high bits |
| Relation for non-negative integers | Multiply by a power of 2 | Integer-divide by a power of 2 |
| Common uses | Creating masks, encoding | Extracting fields, scaling calculations |
9. Bitwise assignment operators
Python provides compound assignment operators corresponding to bitwise operations:
| Operator | Equivalent expression |
|---|---|
&= |
a = a & b |
|= |
a = a | b |
^= |
a = a ^ b |
<<= |
a = a << b |
>>= |
a = a >> b |
Example:
number = 0b1010
number &= 0b1100
print(bin(number)) # 0b1000
number |= 0b0011
print(bin(number)) # 0b1011
number ^= 0b0001
print(bin(number)) # 0b1010
number <<= 1
print(bin(number)) # 0b10100
number >>= 2
print(bin(number)) # 0b101
These operators are commonly used to update status flags, modify permission sets, and process binary fields.
10. Engineering application of bitwise operations: permission management
1. Using binary flags to represent permissions
Suppose the system has four permissions:
- Read permission
- Write permission
- Delete permission
- Admin permission
You can assign an independent binary bit to each permission:
READ = 1 << 0
WRITE = 1 << 1
DELETE = 1 << 2
ADMIN = 1 << 3
Mapping:
| Permission | Binary | Decimal |
|---|---|---|
| READ | 0001 |
1 |
| WRITE | 0010 |
2 |
| DELETE | 0100 |
4 |
| ADMIN | 1000 |
8 |
2. Creating permission combinations
user_permissions = READ | WRITE
print(bin(user_permissions)) # 0b11
At this point, the user has read and write permissions.
3. Determining whether a certain permission is held
def has_permission(permissions, permission):
return (permissions & permission) == permission
user_permissions = READ | WRITE
print(has_permission(user_permissions, READ)) # True
print(has_permission(user_permissions, WRITE)) # True
print(has_permission(user_permissions, DELETE)) # False
With bitwise AND, you can check whether all the bits corresponding to a specified permission are set.
4. Adding Permissions
user_permissions |= DELETE
5. Removing Permissions
Using bitwise NOT together with bitwise AND, you can clear a specified permission:
user_permissions &= ~DELETE
6. Toggling Permissions
Using XOR, you can flip a specified permission:
user_permissions ^= WRITE
If the user originally had the write permission, it is removed after execution; if not, it is added.
7. Complete Example of Permission Management
READ = 1 << 0
WRITE = 1 << 1
DELETE = 1 << 2
ADMIN = 1 << 3
def has_permission(permissions, permission):
return (permissions & permission) == permission
def add_permission(permissions, permission):
return permissions | permission
def remove_permission(permissions, permission):
return permissions & ~permission
def toggle_permission(permissions, permission):
return permissions ^ permission
permissions = READ | WRITE
print("初始权限:", bin(permissions))
permissions = add_permission(permissions, DELETE)
print("添加删除权限:", bin(permissions))
print("是否可以读取:", has_permission(permissions, READ))
print("是否可以管理:", has_permission(permissions, ADMIN))
permissions = remove_permission(permissions, WRITE)
print("移除写入权限:", bin(permissions))
permissions = toggle_permission(permissions, ADMIN)
print("切换管理权限:", bin(permissions))
This approach compresses multiple boolean states into a single integer, saving storage space and making batch operations convenient.
However, a real permission system also needs to handle role inheritance, permission validation, resource scopes, and access control policies; it cannot rely on a single integer flag alone.
XI. Basics of Membership Operations
1. What Are Membership Operations
Membership operations are used to determine whether an object exists within another object.
Python provides two membership operators:
| Operator | Meaning | Return Value |
|---|---|---|
in |
Checks whether an element exists | True or False |
not in |
Checks whether an element does not exist | True or False |
Example:
numbers = [10, 20, 30]
print(20 in numbers) # True
print(40 in numbers) # False
print(40 not in numbers) # True
print(20 not in numbers) # False
Membership operations express an existence check, not a comparison of an element's position within the container.
2. Basic Syntax of Membership Operations
element in container
Or:
element not in container
Membership operations ultimately return a boolean result:
result = "Python" in ["Python", "Java", "Go"]
print(result) # True
print(type(result)) # <class 'bool'>
XII. Membership Operations in Different Data Types
1. Membership Checks in Lists
Lists use membership operations to determine whether an element exists.
numbers = [10, 20, 30, 40]
print(10 in numbers) # True
print(50 in numbers) # False
Membership checks in lists use equality comparison semantics.
values = [1, 2, 3]
print(True in values) # True
This is because in Python:
True == 1
The result is True.
Therefore, when using membership operations to check values of different types, pay attention to Python's equality rules.
2. Membership checks in tuples
Tuples also support in and not in:
colors = ("red", "green", "blue")
print("red" in colors) # True
print("yellow" in colors) # False
List and tuple membership operations have similar semantics, but their underlying storage structures and mutability differ.
3. Membership checks in sets
Sets are very suitable for membership checks.
numbers = {10, 20, 30, 40}
print(20 in numbers) # True
print(50 in numbers) # False
Under normal circumstances, the average time complexity of set membership lookup is O(1).
This is because sets are implemented based on hash tables.
However, note that:
- Set elements must be hashable objects.
- Hash collisions may lead to additional comparisons.
- In the worst case, lookup complexity may degrade.
- The hash and equality implementations of custom objects affect membership checks.
4. Membership checks in dictionaries
When a dictionary performs a membership operation, it checks keys by default, not values.
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
print("name" in user) # True
print("Alice" in user) # False
If you need to check whether a certain value exists, use values():
print("Alice" in user.values()) # True
If you need to check whether a key-value pair exists, you can use items():
print(("name", "Alice") in user.items()) # True
Differences between the three checking methods:
| Expression | Object checked |
|---|---|
key in dict_obj |
Dictionary keys |
value in dict_obj.values() |
Dictionary values |
(key, value) in dict_obj.items() |
Key-value pairs in the dictionary |
5. Membership checks in strings
String membership operations are used to check whether a substring exists.
text = "Python is powerful"
print("Python" in text) # True
print("power" in text) # True
print("Java" in text) # False
String membership checks are case-sensitive:
text = "Python"
print("python" in text) # False
print("Python" in text) # True
If you need to ignore case, you can normalize the case:
text = "Python is powerful"
keyword = "PYTHON"
result = keyword.lower() in text.lower()
print(result) # True
String membership checks target contiguous substrings, not word-level semantic checks.
For example:
text = "programming"
print("gram" in text) # True
print("pro" in text) # True
If you need to check whether a complete word exists, you should use a more appropriate tokenization or regular expression approach.
6. Membership checks in range
range objects also support membership checks:
numbers = range(0, 100, 5)
print(10 in numbers) # True
print(12 in numbers) # False
For a range constructed with standard integer arguments, membership testing can be computed directly from the range and step, without iterating over every element one by one.
7. Membership Tests in bytes and bytearray
bytes and bytearray also support membership operations:
data = b"Python"
print(80 in data) # True
print(90 in data) # False
Integer membership tests check the corresponding byte value.
You can also test with a subsequence:
data = b"Python"
print(b"Py" in data) # True
13. Underlying Mechanism of Membership Operations
1. How Python Executes in
Membership operations are not implemented in the same underlying way for all objects.
For ordinary objects, Python's membership testing protocol generally follows this order:
- First try the object's
__contains__()method. - If no usable
__contains__()is available, try the iteration protocol and compare by iterating over elements. - If the object has no usable iteration protocol, try the old-style sequence protocol, accessing elements by integer index until an
IndexErroroccurs.
This process can be understood as:
flowchart TD
A["Execute element in container"] --> B{"Supports __contains__?"}
B -->|Yes| C["Call __contains__"]
B -->|No| D{"Supports iteration protocol?"}
D -->|Yes| E["Iterate over elements and compare"]
D -->|No| F{"Supports sequence index protocol?"}
F -->|Yes| G["Access items by index"]
F -->|No| H["Raise TypeError"]
C --> I["Convert to boolean result"]
E --> I
G --> I
I --> J["Return True or False"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. The contains Method
__contains__() is Python's special method for membership testing.
For example:
numbers = [1, 2, 3]
print(numbers.__contains__(2)) # True
print(numbers.__contains__(5)) # False
Normally, you should prefer:
2 in numbers
instead of calling the special method directly.