Search code examples
pythonlistmode

Python: items not being removed from list


listsal2 = [1,2,2,3,3,4,5,6,7,8]
listsal3 = []

counter = 0
for i in listsal2:
    item = listsal2.count(i)

    if item > 1:
        counter = item 
        while counter > 1:
            listsal3.append(i)   
            counter = counter - 1




print (listsal3)

I've been working on a mode function but for some reason it keeps the last couple numbers in the list and the more items in the list, the more that don't get removed.

EDIT: just realized I forgot the 2nd part of the code which is now in

EDIT2: code is shrunken down and easier to read

EDIT3: changed code so the duplicate numbers go into a new list but it has the multiple amounts of the list item

Thanks to all for the help I think I've got it now


Solution

  • In your case, even after you account for i=2 once, you go through the list again for 2, since it exists multiple times. This is why 2 and 3 end up in listsal3 twice. Instead, what you want to do is only go through the list once for each unique item.

    listsal2 = [1,2,2,3,3, 4]
    newlist = set(listsal2)
    listsal3 = []
    
    counter = 0
    for i in newlist:
        item = listsal2.count(i)
    
        if item > 1:
            counter = item 
            print counter
            while counter > 1:
                listsal3.append(i)   
                counter = counter - 1
    
    print listsal2, listsal3
    

    To get the unique items from your list, convert it to a set.

    Another way to do it: Simply keep a list containing the counts of each unique element, take the maximum of it, and trace back to the element that it corresponds to.

    newset = set(listsal2)
    newlist = list(set)
    counts = []
    
    for item in newlist:
        counts.append(listsal2.count(item))
    maxcount = max(counts)
    max_occurring_item = newlist[counts.index(maxcount)]