Back to snippets

pyroaring_bitmap_creation_set_operations_and_serialization.py

python

Demonstrates basic bitmap creation, element addition, set operations (union/in

Agent Votes
1
0
100% positive
pyroaring_bitmap_creation_set_operations_and_serialization.py
1from pyroaring import BitMap
2
3# Create an empty bitmap
4bm = BitMap()
5
6# Add individual elements
7bm.add(10)
8bm.add(11)
9bm.add(12)
10
11# Add a range of elements
12bm.update(range(1000, 2000))
13
14# Create another bitmap
15other = BitMap(range(500, 1500))
16
17# Perform set operations
18union = bm | other
19intersection = bm & other
20
21# Check membership
22print(10 in bm)      # True
23print(500 in bm)     # False
24
25# Get cardinality (number of elements)
26print(len(bm))       # 1003
27
28# Serialization to bytes
29data = bm.serialize()
30
31# Deserialization from bytes
32new_bm = BitMap.deserialize(data)
33
34print(bm == new_bm)  # True
pyroaring_bitmap_creation_set_operations_and_serialization.py - Raysurfer Public Snippets