Python - Check if two variables in a list have same value

1087 views python
1

I am new to Python, and am working on a small project when I came across a small logical hindrance. I have an tuple containing 100 string values (say). Now, I want to check if two string elements there in the tuple are same?

So simplified I want to achieve something like this:

arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr', ...)
# A logic to check if any two string elements are same
# eg. if arr[1] == arr[2] or arr[1] == arr[3] or ...
# But checking like this for 100 variables is not feasible
    return True

I tried to do something like this with nested loops:

ctr = 0
arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr', ...)
for m in arr:
    for n in arr:
        if n == m:
            ctr+=1
# 100 because while looping, 100 times every element 
# will be compared with itself
if(ctr > 100):
    return True

...which worked but I think there is a better work around for this. Can anyone provide a possible workaround?

Regards.

answered question

Well, that is not a list it is a tuple

I think this question should be on Code Review

2 Answers

5

If I understand correctly, you can just convert your tuple to a set and check whether it has the same length as the original tuple.

def has_duplicates(iterable):
    l = list(iterable) # in case iterable is an iterator
    return len(set(l)) != len(l)

Demo:

>>> tup = ('abc', 'bcd', 'sdf', 'abc', 'pqr')
>>> has_duplicates(tup)
>>> True
>>> has_duplicates(range(100))
>>> False

Won't work for infinite iterators :)

~edit~

A more general version that does not have to build a potentially long list and set upfront:

def has_duplicates(iterable):
    seen = set()
    for x in iterable:
        if x in seen:
            return True
        seen.add(x)
    return False

Of course, both versions require the elements of your iterable to be hashable.

posted this
12

You can also check this using any keyword and count method from list object:

arr = ('abc', 'bcd', 'sdf', 'abc', 'pqr')

def sameStrings(arr):
  return any(arr.count(elem)>1 for elem in list(arr))

print(sameStrings(arr))

Output:

True

posted this

Have an answer?

JD

Please login first before posting an answer.