Subtract method of counter

Method Name:

subtract

 

Method Signature:

subtract(iterableObjectOrMappingObject)

 

Method Overview:

  • subtract() subtracts the counts of elements present in an iterable object or a mapping object from the counter object.

 

  • subtract() method returns None.

 

  • subtract() changes the counts of elements in the counter object on which the method was called.

 

  • If the iterable object or mapping object does not have all the elements of the counter object only the counts of common elements present in the iterable/mapping object are subtracted from the counts of counter object.

 

Example 1:

import collections

 

# create two boxes

box1 = collections.Counter({"pen":4,"pencil":6,"eraser":3,"coins":4})

box2 = collections.Counter({"pen":2,"pencil":2,"eraser":1,"coins":2})

 

# subtract box2 from box1

ret = box1.subtract(box2)

 

#print box1 contents

print(box1)

 

Output:

Counter({'pencil': 4, 'pen': 2, 'eraser': 2, 'coins': 2})

 

Example 2:

import collections

 

# Create a counter of few alphabets and their counts

c1 = collections.Counter({"a":4,"b":6,"c":3,"d":4})

 

# Create a tuple with few alphabets

iterableObject  = ("a","b")

 

# Subtract the counts of iterable(tuple) elements from the element counts of counter

ret = c1.subtract(iterableObject)

 

# print the counter

print(c1)

 

Output:

Counter({'b': 5, 'd': 4, 'a': 3, 'c': 3})

 


Copyright 2024 © pythontic.com