2

I'm a beginner with Python. Let me show you my code below and I'll describe my problem.

    random_list=['a','b','c','b','d','m','n','n']
    duplicates=[] 
    for value in random_list:
      if random_list.count(value) > 1:
        if value is not duplicates:
         duplicates. Append(value)
    

print(duplicates)

Below is what happens when I run the code.

    []
    ['b']
    ['b']
    ['b', 'b']
    ['b', 'b']
    ['b', 'b']
    ['b', 'b', 'n']
    ['b', 'b', 'n', 'n'

The problem is that it shows me the duplicates however, it shows them too many times. How do I tell Python that I only want to show the duplicates once? Example: ['b','n']. Please note, I'm not trying to eliminate the duplicates in my list, I'm trying to show them.

I've put tried different controls in my loops but they failed. They only showed one duplicate.

1
  • How are you getting multiple outputs? print(duplicates) is not in the loop.
    – Barmar
    Commented Sep 22, 2023 at 18:55

3 Answers 3

3

Use collections.Counter to count the values and list-comprehension to get the duplicates:

from collections import Counter

random_list = ["a", "b", "c", "b", "d", "m", "n", "n"]

duplicates = [c for c, v in Counter(random_list).items() if v > 1]
print(duplicates)

Prints:

['b', 'n']
2
  • 2
    Using a collections.Counter is a really good idea, it will make the code O(n) rather than O(n**2) (since list.count needs to scan the whole list each time).
    – Blckknght
    Commented Sep 22, 2023 at 18:57
  • 1
    @Blckknght Yeah, it's top. Commented Sep 22, 2023 at 19:00
1

The inner if statement you have is already close to doing what you want, but you've picked the wrong comparison operator. Rather than is not, you want not in. You can also combine the two ifs into a single statement with and:

random_list=['a','b','c','b','d','m','n','n']
duplicates=[] 
for value in random_list:
  if random_list.count(value) > 1 and value not in duplicates:
     duplicates.append(value)
print(duplicates)
0
0

You can create a duplicates list by checking how many times an item appears in the original list:

Code
random_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates_list = list({item for item in random_list if random_list.count(item) > 1})
print(duplicates_list)
Output
['n', 'b']

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.