Question

I have a 5-element list and I want to know if there are 2 or 3 equal elements (or two equal and three equal). This "check" would be a part of if condition. Let's say I'm too lazy or stupid to write:

if (a==b and c==d and c==e) or .......... or .........

i know it might be written like this, but not exactly how:

if (a==b and (c==b and (c==e or .... 

How do I do it? I also know that you can write something similar to this:

if (x,y for x in [5element list] for y in [5element list] x==y, x not y: 
Was it helpful?

Solution

If you just want to check for multiple occurences and the objects are of an hashable type, the following solution could work for you.

You could create a list of your objects

>>>l = [a, b, c, d, e]

Then, you could create a set from the same list and compare the length of the list and the length of the set. If the set has less elements than the list, you know you must have multiple occurences.

>>>if (len(set(l)) < len(l)):
    ...

OTHER TIPS

Use count. You just want [i for i in myList if myList.count(i) > 1]. This list contains the repeated elements, if it's non-empty you have repeated elements.

Edit: SQL != python, removed 'where', also this'll get slow for bigger lists, but for 5 elements it'll be fine.

You can use collections.Counter, which counts the occurrence of every element in your list. Once you have the count, just check that your wanted values (2 or 3) are present among the counts.

from collections import Counter
my_data = ['a', 'b', 'a', 'c', 'd']
c=Counter(my_data)
counts = set(c.values())
print 2 in counts or 3 in counts
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top