Reputation: 3241
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?
Upvotes: 5
Views: 23694
Reputation: 1268
>>> 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]
Upvotes: 0
Reputation: 55956
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]
Upvotes: 5
Reputation: 16525
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
Upvotes: 2
Reputation: 222188
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
Upvotes: 1
Reputation: 375594
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.
Upvotes: 10