0

When I loop over this list via the given code below:

my_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

for i in my_list:
    count = my_list.count(i)
    if count > 1:
        print(i)

it gives me an output ['b','b','n','n'].

How can I modify my code to just give the duplicated letter only, not each letter in the list without using sets?

2 Answers2

0

Efficient Solution:

Here update a dictionary counter, and whenever a duplicate is found it's added to a set.

my_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

char_counter = {}
duplicates = set()
for x in my_list:
    if x not in char_counter.keys():
        char_counter[x] = 1
    else:
        char_counter[x] += 1
        duplicates |= {x}

print(duplicates)

One liner:

my_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
print(set([x for x in my_list if my_list.count(x) > 1]))

Quick Fix:

my_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

duplicates = []
for i in my_list:
    count = my_list.count(i)
    if count > 1 and i not in duplicates:
        duplicates.append(i)

print(duplicates)
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
0

Try Counter

my_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
from collections import Counter
duplicates = [item for item, count in Counter(my_list).items() if count > 1]

OUTPUT:

['b','b','n','n']
Suryaveer Singh
  • 577
  • 2
  • 13