![]() |
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() FunctionCounter.update(iterable_or_mapping) Python Counter.update() Method ExamplesBelow are some of the examples by which we can understand about Counter.update() method in Python: Updating Counts from an IterableIn this example, the counts of ‘apple’ and ‘banana’ are updated based on the elements in the fruits list.
Output Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1}) Combining Counters Using Counter.update() FunctionIn this example, the counts of elements in counter1 are updated based on the counts in counter2.
Output Combined Counter: Counter({'b': 6, 'a': 4, 'c': 2}) Updating Counts with Generator ExpressionIn this example, we use a generator expression to convert each word to lowercase before updating the counts in the word_counter.
Output Updated Counter: Counter({'apple': 5, 'banana': 2, 'orange': 1}) |
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |