The Bag Abstract Data Type in Python

A bag is a container that stores a collection in which duplicate values are allowed. The items, each of which is individually stored, have no particular order but they must be comparable

  • Bag(): Creates a bag that is initially empty.
  • length (): Returns the number of items stored in the bag. Accessed using the len() function.
  • contains ( item ): Determines if the given target item is stored in the bag and returns the appropriate boolean value. Accessed using the in operator.
  • add( item ): Adds the given item to the bag.
  • remove( item ): Removes and returns an occurrence of item from the bag. An exception is raised if the element is not in the bag.
  • iterator (): Creates and returns an iterator that can be used to iterate over the collection of items

Example Bag Abstract Data Type

myBag = Bag()
myBag.add( 19 )
myBag.add( 74 )
myBag.add( 23 )
myBag.add( 19 )
myBag.add( 12 )
value = int( input("Guess a value contained in the bag.") )
if value in myBag:
print( "The bag contains the value", value )
else :
print( "The bag does not contain the value", value )

#pgm: (modified main() from
from linearbag import Bag
from date import Date
def main():
bornBefore = Date( 6, 1, 1988 )
bag = Bag()
# Extract dates from the user and place them in the bag.
date = promptAndExtractDate()
while date is not None :
bag.add( date )
date = promptAndExtractDate()
# Iterate over the bag and check the age.
for date in bag :
if date <= bornBefore :
print( "Is at least 21 years of age: ", date )

Leave a Comment