Counting elements: What is the difference between these methods?

Viewed 15

my first question here so I hope everything goes well. I am learning python and during my readings I found different methods of counting elements in an iterable.
The first one:

    from collections import defaultdict
    d = defaultdict(int)
    L = [1, 2, 3, 4, 2, 4, 1, 2]
    for i in L:
       d[i] += 1
    print(d)

The second one:

    from collections import Counter
    Counter([1, 2, 3, 4, 2, 4, 1, 2])

The third one:

    import collections
    counter = collections.Counter()
    L = [1, 2, 3, 4, 2, 4, 1, 2]
    for item in L:
       counter[item] += 1
    print(counter)

Actually I have two questions about these methods:

  1. What's the difference between the first two? I mean the data type of d is collections.defaultdict and basically is like a dictionary from my understanding, on the other hand the data type of Counter('Hi') is collections.Counter but it seems to me that this also stores data like a dictionary so what's the difference between these two objects?
  2. I cannot grasp the theoretical difference between the last two methods, I would say that in one we don't instantiate the Counter object in the other yes, but I am not sure.
0 Answers
Related