user11620448
user11620448

Reputation:

Why are my duplicate items occuring twice in a row?

I am trying to find out a list of all duplicate items in a list.

My code:

list=['see','eat','feel','see','eat']
i=0
j=0
l=[]

for i in range(len(list)-1):
    j=i+1
    for j in range(len(list)):
        if (list[i]==list[j]):
            l.append(list[i])

print(l)

Expected output:

['see', 'eat']

Actual output:

['see', 'see', 'eat', 'eat', 'feel', 'see', 'see']

The duplicates should only be there in the list. Where am I going wrong??

Upvotes: 1

Views: 252

Answers (5)

Pritesh Wani
Pritesh Wani

Reputation: 11

try this:

l=[]

for i in list:
    c=0
    for j in list:
        if i==j :
            c+=1
    if c!=1:
        flag=0
        for k in l:
            if k==i:
                flag=1
        if flag==0:
            l.append(i)
print(l) 

in this code i used three loops 1. for repetating each value to check weater it is duplicate or not 2. for repetating each value and compare them togather . note repting values will whave value in c is 2 or more 3.to check weather the values stored in l are not repeating

Upvotes: 0

Daniel
Daniel

Reputation: 42748

You have to loops, so you get all combinations of pairs of two words.

Best, use only one loop, and keep track of duplicate elements:

seen = set()
duplicates = set()
for item in list:
    if item in seen:
        duplicates.add(item)
    else:
        seen.add(item)

Upvotes: 0

Dev Khadka
Dev Khadka

Reputation: 5451

you can do it using list comprehension like below

ls=['see','eat','feel','see','eat']

[ls[i] for i in range(len(ls)) for j in range(len(ls)) if (j>i and ls[i]==ls[j])]

Upvotes: 0

RemcoGerlich
RemcoGerlich

Reputation: 31250

These two lines:

j=i+1
for j in range(len(list)):

First you give some value to j, then in the for loop you let it loop over 0 up to len(list) and the value is forgotten. That wasn't what you meant.

Instead

for j in range(i+1, len(list)):

would do what you intended, I think.

But that still gives you problems if some value occurs, say, thrice.

Upvotes: 2

AKX
AKX

Reputation: 168834

You can just use the collections.Counter() standard library class for a more efficient approach.

import collections

lst = ['see','eat','feel','see','eat']
lst_counts = collections.Counter(lst)
duplicates = [value for (value, count) in lst_counts.items() if count > 1]

print(duplicates)

outputs

['see', 'eat']

Upvotes: 3

Related Questions