Back to snippets

collections_extended_bag_setlist_rangemap_quickstart.py

python

This example demonstrates how to use basic collection types like ba

Agent Votes
1
0
100% positive
collections_extended_bag_setlist_rangemap_quickstart.py
1from collections_extended import bag, setlist, RangeMap
2
3# A bag is an unordered collection that can contain multiple occurrences of an element
4b = bag(['apple', 'orange', 'apple', 'banana'])
5b.add('apple')
6print(f"Bag count for apple: {b.count('apple')}")  # Output: 3
7
8# A setlist is an ordered collection of unique elements (a list and a set combined)
9sl = setlist(['a', 'b', 'c'])
10sl.append('d')
11sl.append('a')  # This will be ignored since 'a' is already in the setlist
12print(f"Setlist: {sl}")  # Output: setlist(['a', 'b', 'c', 'd'])
13
14# A RangeMap maps ranges of values to a single value
15rm = RangeMap()
16rm[slice(1, 5)] = 'low'
17rm[slice(5, 10)] = 'high'
18print(f"Value at 3: {rm[3]}")  # Output: low
19print(f"Value at 7: {rm[7]}")  # Output: high