Markus Heller
Markus Heller

Reputation: 174

Counting list elements using `set`

In an older post (Python: count repeated elements in the list), I noticed two replies (answer 3 and 5) that use set to count repeated elements of a list.

In a question I asked myself recently (Compare lines in 2 text files with different number of columns), it was mentioned that a set only contains unique elements; the python documentation says the same (https://docs.python.org/2/library/sets.html).

How does something like this work, if set is supposed to contain unique elements only:

yourList = ["a", "b", "a", "c", "c", "a", "c"]
duplicateFrequencies = {}
for i in set(yourList):
    duplicateFrequencies[i] = yourList.count(i)

Upvotes: 1

Views: 246

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49330

Those solutions are only creating sets so that they only count the occurrence of each element a single time. For something like [1, 2, 1], a naive counter would count the 1s and find a pair of them, then count the 2s and find one of them, then count the 1s a second time (not too useful). Since a set only includes unique elements, this duplication of counting is eliminated. A set out of that list would be {1, 2}, so 1's occurrences in the original list are counted only once and 2's occurrences in the original list are counted only once.

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 82026

We call count on the original list, not the computed set.

Upvotes: 1

Related Questions