Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove elements from a list that appear less than k = 2?

I am trying to keep elements of a list that appear at least twice, and remove the elements that appear less than twice.

For example, my list can look like:

letters = [‘a’, ‘a’, ‘b’, ‘b’, ‘b’, ‘c’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to get a list with the numbers that appear at least twice, to get the following list:

letters_appear_twice = [‘a’, ‘b’].

But since this is part of a bigger code, I don’t know exactly what my lists looks like, only that I want to keep the letters that are repeated at least twice. But for the sake of understanding, we can assume I know what the list looks like!

I have tried the following:

”’

letters = ['a', 'a', 'b', 'b', 'b', 'c']

for x in set(letters):
    if letters.count(x) > 2:
        while x in letters:
            letters.remove(x)

print(letters)

”’

But this doesn’t quite work like I want it too…

Thank you in advance for any help!

>Solution :

letters = ['a', 'a', 'b', 'b', 'b', 'c']

res  = []
for x in set(letters):
    if letters.count(x) >= 2:
        res.append(x)
print(res)

Prints:

['b', 'a']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading