-3

Is it possible to count the duplicates from a list?

Let’s say I have this list:

my_list = [1, 2, 3, 6, 2, 1, 6]

And i want an output like this:

my_list_duplicates = {1: 2, 2: 2, 3: 1, 6: 2}

Is that possible?

CB_MS
  • 3
  • 1
    Does this answer your question? [How do I find the duplicates in a list and create another list with them?](https://stackoverflow.com/questions/9835762/how-do-i-find-the-duplicates-in-a-list-and-create-another-list-with-them) – blackbrandt Sep 20 '21 at 13:53
  • 2
    Does this answer your question? [python equivalent of R table](https://stackoverflow.com/questions/25710875/python-equivalent-of-r-table) – Sotos Sep 20 '21 at 13:54
  • 1
    Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – no comment Sep 20 '21 at 14:19

5 Answers5

3

The absolute easiest way is to use the collections.Counter object from the standard library:

>>> import collections
>>> my_list = [1, 2, 3, 6, 2, 1, 6]
>>> dict(collections.Counter(my_list))
{1: 2, 2: 2, 3: 1, 6: 2}
AKX
  • 152,115
  • 15
  • 115
  • 172
0

collections.Counter does exactly what you want.

orlp
  • 112,504
  • 36
  • 218
  • 315
0

If you do not want to use an inbuilt function, you could use a hash map to store the count of the values as your iterate through the list

my_list = [1, 2, 3, 6, 2, 1, 6]
my_list_duplicates = {}

for i in my_list:
    if my_list_duplicates.get(i):
        my_list_duplicates[i] += 1
    else:
        my_list_duplicates[i] = 1
    
print(my_list_duplicates)        

Output

{1: 2, 2: 2, 3: 1, 6: 2}
vnk
  • 1,060
  • 1
  • 6
  • 18
0

1.You can use Counter from collections package .

from collections import Counter
my_list = [1, 2, 3, 6, 2, 1, 6]
list_1 = Counter(my_list)
print(list_1)

2.second option is you can iterate it in a loop for each value to find its duplicate and store them in a dictionary .

my_list = [1, 2, 3, 6, 2, 1, 6]
duplicate_dict = {i: my_list.count(i) for i in my_list
print(duplicate_dict)
codette
  • 83
  • 1
  • 7
-3

You can do that with count:

my_list_duplicates = {i: my_list.count(i) for i in my_list}
Charalarg
  • 75
  • 1
  • 9