0

I realize this question has been asked an infinite number of number of times, but I have spin on it. I am attempting to check a list of elements for duplicates and print either of two responses depending on if there are/are not any duplicates.

I do not wish to wish to remove the duplicates, but simply display a unique message for either of two situations: if there are or are not any duplicates within the string.

I have the following script I created, but it prints seven lines. I wish to reduce to it to one sentence. Thanks.

my_list.sort()

for i in range(0,len(my_list)-1):   
    if my_list[i] == my_list[i+1]: 
        duplicates += 1 
    elif duplicates > 0:
        print "There were duplicates found."
    else:
        print "There were no duplicates"

I spent a lot of time on the internet trying to find a solution for my problem before asking the community--I apologize in advance if this a very, very simple problem.

1
  • Move the last four lines out of the for loop Commented Apr 13, 2014 at 18:59

1 Answer 1

4

Maybe the most straightforward way is to take advantage of the fact that a set will eliminate any duplicates found in the iterable used to create it. If the length of the set of letters in a string is different than the length of the string, there must be at least one duplicate.

>>> def areDupes(s):
...    return len(set(s)) != len(s)
...
>>> areDupes('abcdef')
False
>>> areDupes('abcdeff')
True
Sign up to request clarification or add additional context in comments.

4 Comments

Could you adapt this to make it work also for duplicate words and not just duplicate characters?
@Private It would work equally fine with a list without changes because both strings and lists are iterable.
exactly -- it works with any iterable. To check dupe words in a string, just call areDupes(s.split(' '))
@bgporter That's what I was thinking about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.