1

I'm currently making a Sudoku game because the logic behind the validation is very fun to code and there are plenty of ways to do it.

My question is very simple. Is there any function in python that checks if a value is present in a list more than once?

I made a little function that does this, and it works:

def IsRepeated(list):
    overlap = False 
    for index, val in enumerate(list):
        for step in range(index+1, len(list)):
            if val == list[step]:
                overlap = True
                break
        if overlap:
            break
    return overlap

The input is a list like a = [1,2,3,4,5,6]

This works perfectly, but I want to make sure there's no other better way to do this, as there typically is.

André Rocha
  • 123
  • 7
  • Yes, for example, `[1,1,1,2,2].count(1) == 3`. If `count(x)` returns something greater than one, then `x` is present in the list more than once. Calling this function multiple times is inefficient, though, since it'll go through the whole list each time. – ForceBru Mar 09 '19 at 16:04
  • 1
    You can use `if len(a) != len(set(a)):` – panda-34 Mar 09 '19 at 16:07

3 Answers3

3

Example using the Python console:

>>> a=[1,2,3,4,5,6,6]
>>> set(a)
{1, 2, 3, 4, 5, 6}
>>> len(set(a))
6
>>> len(a)
7
>>> if len(set(a)) != len(a):
...    print("Yes, there is some value present in a list more than once.")
...
Yes, there is some value present in a list more than once.
s3n0
  • 596
  • 3
  • 14
  • Thanks. Is there any way to check which one was duplicate without making a whole different function? Right now I don't need it but it might be useful in the future – André Rocha Mar 09 '19 at 16:27
  • Of course. Again using a set + one-line function. For example: https://stackoverflow.com/a/15155286/9808870 quoted soruce code: `set([x for x in a if a.count(x) > 1])` – s3n0 Mar 09 '19 at 16:34
2

There is no exact function that does this purpose. But you can make use of Counter to make it more efficient and short:

from collections import Counter

def IsRepeated(lst):
    return any(v > 1 for v in Counter(lst).values())

a = [1,2,3,4,5,6]
print(IsRepeated(a))
# False

Btw, don't name your list as list as it shadows the built-in.

Austin
  • 25,759
  • 4
  • 25
  • 48
1

For a=[1,2,3,4,5,6,6]:

np.unique(a)[np.where(np.array([len(np.where(a==i)[0]) for i in np.unique(a)])>1)[0]]

This will give you a list of elements that appear more than once.

razimbres
  • 4,715
  • 5
  • 23
  • 50