Python Forum

Full Version: How to keep duplicates and remove all other items in list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to make a function that returns a new list where each item that appears an odd number of times in l is removed

For example,
A list like this:
['1', '2','2','4', '5','1','6','2', '6']

Becomes:
['1','2','2','1','6','6']
(doesn't matter what order)

I am trying to use the count method for lists and to determine the number of occurrences for each item in the list and append it to a new one but I can't seem to make it work

Here is what I have so far:

def clean_up_board(l):
     playable_board=[]
     for i in range(len(l)):
        num_of_occ=l.count(i)
        if num_of_occ%2==0:
            playable_board.append(i)
    return playable_board
#!/usr/bin/python3
list = ['1', '2','2','4', '5','1','6','2', '6']

def clean_up_board(l):
     playable_board = [ ]
     for e in l:
        num_of_occ = l.count(e)
        if num_of_occ % 2 == 0:
            playable_board.append(e)
     return playable_board

print(clean_up_board(list))
Output:
['1', '1', '6', '6']