Open In App

Python Counter.update() Method

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python’s Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counter.update() method.

What is Python Counter.update() Method?

The Counter.update() method updates the counts of elements in a Counter object based on the elements provided in an iterable or another Counter object. It takes an iterable or a mapping (such as another Counter) as its argument and increments the counts of elements accordingly.

Syntax of Counter.update() Function

Counter.update(iterable_or_mapping)

Python Counter.update() Method Examples

Below are some of the examples by which we can understand about Counter.update() method in Python:

Updating Counts from an Iterable

In this example, the counts of ‘apple’ and ‘banana’ are updated based on the elements in the fruits list.

Python3
from collections import Counter

# Initial Counter
fruit_counter = Counter({'apple': 2, 'banana': 1})

# Update counts from an iterable
fruits = ['apple', 'banana', 'apple', 'orange', 'apple']
fruit_counter.update(fruits)

print("Updated Counter:", fruit_counter)

Output
Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1})

Combining Counters Using Counter.update() Function

In this example, the counts of elements in counter1 are updated based on the counts in counter2.

Python3
from collections import Counter

# Initial Counters
counter1 = Counter({'a': 3, 'b': 2})
counter2 = Counter({'a': 1, 'b': 4, 'c': 2})

# Combine counters
counter1.update(counter2)

print("Combined Counter:", counter1)

Output
Combined Counter: Counter({'b': 6, 'a': 4, 'c': 2})

Updating Counts with Generator Expression

In this example, we use a generator expression to convert each word to lowercase before updating the counts in the word_counter.

Python3
from collections import Counter

# Initial Counter
word_counter = Counter({'apple': 2, 'banana': 1})

# Update counts from a generator expression
words = ('apple', 'banana', 'apple', 'orange', 'apple')
word_counter.update((word.lower() for word in words))

print("Updated Counter:", word_counter)

Output
Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1})

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads