Python Forum
How to keep duplicates and remove all other items in list?
Thread Rating:
  • 3 Vote(s) - 3.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to keep duplicates and remove all other items in list?
#1
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
Reply
#2
#!/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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to sort a list with duplicates and return their unique indices. Echoroom 3 3,476 Sep-23-2022, 07:53 AM
Last Post: deanhystad
  help with adding duplicates elements together in a list 2ECC3O 5 2,026 Sep-10-2022, 07:11 AM
Last Post: 2ECC3O
  How to remove extra space from output list? longmen 3 1,786 May-05-2022, 11:04 PM
Last Post: longmen
  Collisions for items in a list Idents 3 2,293 Apr-06-2021, 03:48 PM
Last Post: deanhystad
  Removing items in a list cap510 3 2,345 Nov-01-2020, 09:53 PM
Last Post: cap510
  Dealing with duplicates to an Excel sheet DistraughtMuffin 6 3,268 Oct-28-2020, 05:16 PM
Last Post: Askic
  Help with Recursive solution,list items gianniskampanakis 8 3,577 Feb-28-2020, 03:36 PM
Last Post: gianniskampanakis
  Removing items from list slackerman73 8 4,421 Dec-13-2019, 05:39 PM
Last Post: Clunk_Head
  duplicates nsx200 3 2,429 Nov-12-2019, 08:55 AM
Last Post: nsx200
  Exercise list remove duplicates RavCOder 9 5,270 Oct-23-2019, 04:16 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020