Reputation: 174
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
Reputation: 49330
Those solutions are only creating set
s 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 1
s and find a pair of them, then count the 2
s and find one of them, then count the 1
s 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