Anant Vikram Singh
Anant Vikram Singh

Reputation: 109

my python code is not working.....i want to find if the entered list contains duplicate items

I want to use this function to find duplicate items in my list, but this code is not working:

p = "enter a list\n"
t = raw_input(p)
def has_duplicate(t):
   o = sorted(t)
   i = 0
   while i < len(o):
       if o[i] == o[i + 1]: 
           print "the list has duplicates"
       elif o[i] != o[i+1]:        
           i += 1
       if i >= len(o):
         print "the list has no duplicate"

It gives me an error saying has_duplicates not defined.

Upvotes: 2

Views: 79

Answers (3)

sberry
sberry

Reputation: 132098

As @mgilson commented, your issue is you are calling the function incorrectly (has_duplicates vs has_duplicate) however...

The most straight forward way to do this is using a set and comparing len.

def has_duplicates(t):
    return len(set(t)) != len(t)

If you take an iterable and wrap it in a set you will end up with only unique items. If the length of the set is the same as your original iterable then you have no duplicates. If the length is different (will always be equal to or smaller) then you have duplicates which were removed when converting to a set type.

Upvotes: 2

Hackaholic
Hackaholic

Reputation: 19753

you might be calling function has_duplicates but you have defined has_duplicate function.

try to call has_duplicate

Upvotes: 0

sudheesh shetty
sudheesh shetty

Reputation: 368

First thing is you do list_name.sort(). Other easy way to find duplicates is

len(your_list)!=len(set(your_list))

Upvotes: 1

Related Questions