Home > database >  Again looping issue
Again looping issue

Time:03-24

I just wrote a simple bunch of code, which had to remove duplicates in list, but there was an issue. Can somebody explain me why it is skipping number 3 ?

lis = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]
for i in lis:
    while lis.count(i) > 1:
        print(f'removing {i} ... ')
        lis.remove(i)
        print(lis.count(i))
print(lis)

CodePudding user response:

Just take your list, convert it to a set and then back to a list:

listofthings = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]

newlist=list(set(listofthings))

print(newlist)

CodePudding user response:

dont use list.remove() if u dont want to remove all 3s or all 1s

listofthings = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]


for things in listofthings:
    exists = 1
    obj = things
    cnt = 0
    for things in listofthings:
       cnt = cnt   1
       dup = things
       if dup == obj:
          exists = exists   1 
       if exists == 2:
           del listofthings[cnt]   
         
  • Related