subtract method of counter

subtract() method subtracts counts of counter objects from the counts of an iterable object or a mapping object

Counter Updated 23 Mar 2017 1 min read

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

python
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

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

Example 2

python
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

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