Change language

Counters in Python | Set 1 (initialization and update)

|

What is a container?
Containers — these are objects that contain objects. They provide a way to access and iterate over contained objects. Examples of built-in containers are Tuple, List, and Dictionary. Others are included in the Collections module.

Counter — it is a subclass of dict. Hence, it is an unordered collection in which the elements and their corresponding values ​​are stored as a dictionary. This is equivalent to a bag or a multitude of other languages.

Syntax:
.Counter class collections ([iterable-or-mapping])

Initialization:
The counter constructor can be called in any of the following ways:

  • With a sequence of items
  • With a dictionary containing keys and numbers
  • With keyword arguments mapping line names to counters
  • An example of each type of initialization:

    # Python program to show different ways creation
    # Counter

    from collections import Counter

     
    # With a sequence of items

    print Counter ([ ’B’ , ’B’ , ’ A’ , ’B’ , ’ C’ , ’A’ , ’ B’ , ’B’ , ’A’ , ’ C’ ])

     
    # with dictionary

    print Counter ({ ’A’ : 3 , ’B’ : < / code> 5 , ’C’ : 2 })

      
    # with keyword arguments

    print Counter (A = 3 , B = 5 , C = 2 )

    The output of all three lines is the same:

     Counter ({’B’: 5,’ A’: 3, ’C ’: 2}) Counter ({’ B’: 5, ’A’: 3,’ C’: 2}) Counter ({’B’: 5,’ A’: 3, ’C’: 2}) 

    Update:
    We can also create an empty counter like this:

     coun = collections.Counter () 

    And we can It can be updated via the update () method. Syntax for the same:

     coun.update (Data) 

    # Python program to demonstrate update ()

    from collections import Counter

    coun = Counter ()

     

    coun.update ([ 1 , 2 , 3 , 1 , 2 , 1 , 1 , 2 ])

    print (coun)

      

    coun.update ([ 1 , 2 , 4 ])

    print (coun)

    Output:

     Counter ({1: 4, 2: 3, 3: 1}) Counter ({1: 5, 2: 4, 3: 1, 4: 1}) 
    • Data can be provided in any of three ways, as indicated in the initialization, and the counter data will be incremented, not replaced.
    • The score can be either zero or negative.

      # Python program to demonstrate what counts < br /> # Counter can be 0 or negative

      from collections import Counter

        

      c1 = Counter (A = 4 , B = 3 , C = 10 )

      c2 = Counter (A = 10 , B = 3 , C = 4

       
      c1.subtract (c2)

      print (c1)

      Exit:

       Counter ({’c’: 6,’ B’: 0, ’A’: -6}) 
    • We can use Counter to count individual list items or other collections.

      # An example program where different elements of the list
      # counted using counter

      from collections import Counter

       
      # Create list

      z = [ ’ blue’ , ’red’ , ’blue’ , ’ yellow’ , ’blue’ , ’ red’ ]

       
      # Count individual items and print counter

      print (Counter (z))

      Output:

       Counter ({’blue’: 3,’ red’: 2 , ’yellow’: 1}) 

    This article is updated by Mayank Rawat If you love Python.Engineering and would like to contribute, you can also write article using contribute.python.engineering or by mailing article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

    Shop

    Learn programming in R: courses

    $

    Best Python online courses for 2022

    $

    Best laptop for Fortnite

    $

    Best laptop for Excel

    $

    Best laptop for Solidworks

    $

    Best laptop for Roblox

    $

    Best computer for crypto mining

    $

    Best laptop for Sims 4

    $

    Latest questions

    NUMPYNUMPY

    Common xlabel/ylabel for matplotlib subplots

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    12 answers

    NUMPYNUMPY

    Flake8: Ignore specific warning for entire file

    12 answers

    NUMPYNUMPY

    glob exclude pattern

    12 answers

    NUMPYNUMPY

    How to avoid HTTP error 429 (Too Many Requests) python

    12 answers

    NUMPYNUMPY

    Python CSV error: line contains NULL byte

    12 answers

    NUMPYNUMPY

    csv.Error: iterator should return strings, not bytes

    12 answers

    News


    Wiki

    Python | How to copy data from one Excel sheet to another

    Common xlabel/ylabel for matplotlib subplots

    Check if one list is a subset of another in Python

    sin

    How to specify multiple return types using type-hints

    exp

    Printing words vertically in Python

    exp

    Python Extract words from a given string

    Cyclic redundancy check in Python

    Finding mean, median, mode in Python without libraries

    cos

    Python add suffix / add prefix to strings in a list

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    Python - Move item to the end of the list

    Python - Print list vertically