5

I basically have an array of 50 integers, and I need to find out whether any of the 50 integers are equal, and if they are, I need to carry out an action.

How would I go about doing this? As far as I know there isn't currently a function in Python that does this is there?

5 Answers 5

10

If you mean you have a list and you want to know if there are any duplicate values, then make a set from the list and see if it's shorter than the list:

if len(set(my_list)) < len(my_list):
    print "There's a dupe!"

This won't tell you what the duplicate value is, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! One more thing though, if there is a duplicate value within the list, why will the length of the the list change when converted to a set? Do sets automatically remove duplicates? Thanks
5

If you have Python 2.7+ you can use Counter.

>>> import collections
>>> input = [1, 1, 3, 6, 4, 8, 8, 5, 6]
>>> c = collections.Counter(input)
>>> c
Counter({1: 2, 6: 2, 8: 2, 3: 1, 4: 1, 5: 1})
>>> duplicates = [i for i in c if c[i] > 1]
>>> duplicates
[1, 6, 8]

2 Comments

This is probably the best solution if you need to know which number appears more than once.
nice I did not know this one. Better than my answer indeed (+1)
2

If your actions need to know the number or how many times that number gets repeated over your input list then groupby is a good choice.

>>> from itertools import groupby
>>> for x in groupby([1,1,2,2,2,3]):
...     print x[0],len(list(x[1]))
... 
1 2
2 3
3 1

The first number is the element and the second the number of repetitions. groupby works over a sorted list so make sure you sort your input list, for instance.

>>> for x in groupby(sorted([1,1,2,4,2,2,3])):
...     print x[0],len(list(x[1]))
... 
1 2
2 3
3 1
4 1

Comments

1

You can convert the list to a Set, and check their lengths.

>>> a = [1, 2, 3]
>>> len(set(a)) == len(a)
True
>>> a = [1, 2, 3, 4, 4]
>>> len(set(a)) == len(a)
False

Comments

0
>>> arbitrary_list = [1, 1, 2, 3, 4, 4, 4]
>>> item_occurence = dict([(item, list.count(item)) for item in arbitrary_list])
{1: 2, 2: 1, 3: 1, 4: 3}

If you want to see which values are not unique you can get a list of those values by

>>> filter(lambda item: item_occurence[item] > 1, item_occurence)
[1, 4]

Comments

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.