ScruffySnub
ScruffySnub

Reputation: 11

Check a list for another instance of its currently referenced value

wheels = [wheel_1,wheel_2,wheel_3,wheel_4,wheel_5]

for wheel in wheels:
    while wheel in wheels.remove(wheel):

Trying to check if the list contains duplicates, so I tried comparing the current value to the list that contains it, minus the value. Even if an item is only in the list once, it still gets caught, which makes me thing the .remove isn't doing what I think it's doing.

Upvotes: 1

Views: 51

Answers (3)

Karthik
Karthik

Reputation: 11

When you for loop iterates wheel(list element) in wheels.. Say it takes wheel_1 in the first iteration. Then you are checking if wheel_1 is in wheels. Where wheels is [wheels_1,wheels_2,.....] so when it does exists in wheels it is removed. Thus list becomes [wheel_2,wheel_2,.....] This happens for every element and thus you end up with an empty list list.remove(list_item) is doing its job here.

Your logic is incorrect.

What you want to do is to set a counter and remove the element if there are more than one presence of the list element in the list.

You should also refer "set" in python. It is a list with no repeatitions.

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

If you only want to check if duplicate exists, you can use set. set contains unique element. So, logic is simple, if length of your list is equal to length of the set, then you have no duplicate.

if len(wheels)==len(set(wheels)):
    print "No duplicate"
else:
    print "Duplicate exists"  

But, if you are interested about what are those duplicate elements, you can consider itertools.Counter which returns you a dictionary with an element of an iterable as key and frequency of that element as value.

from collections import Counter
c = Counter(a)
for key,value in c.iteritems():
    if value>1:
        print key," exists ",value, " times "  

Upvotes: 1

William
William

Reputation: 2935

Why don't you just use .count() to check for duplicates?

wheels = [wheel_1,wheel_2,wheel_3,wheel_4,wheel_5]

for wheel in wheels:
    if wheels.count(wheel) > 1:
        print("duplicate")

Upvotes: 1

Related Questions