Bags
Introduction / Definition
A bag is a collection model in which repeated occurrences or multiple associations can be represented. Unlike a set, a bag can preserve multiplicity, meaning that the number of occurrences of a value can matter. Bags are useful for frequencies, inventories, and one-to-many relationships. The exact implementation of a bag depends on the collection system being used.
Syntax
bag = \[A, A, B\]
count(bag, A) -> 2
Detailed Explanation
Bags can be understood by identifying its purpose, the rules that govern it, and the way it affects program behavior. The concept should be separated from its particular syntax so that learners can recognize the same idea across different programming languages. A useful way to study it is to start with a small example, trace what happens step by step, and then consider the benefits and limitations. This approach builds both conceptual understanding and practical programming skill.
Example
bag = \['apple', 'apple', 'orange'\]
print(count(bag, 'apple'))
Output
2
Important Points / Notes
- Multiplicity can be meaningful.
- A bag differs from a set because duplicates matter.
- Bags suit frequency-like data.
- Implementation details vary by language.
- Use the abstraction that matches the data requirement.
Mini Practice Question
If a bag contains [A,A,B,C,C,C], what is the count of C?