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 == arr or arr == arr 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?
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)
>>> tup = ('abc', 'bcd', 'sdf', 'abc', 'pqr') >>> has_duplicates(tup) >>> True >>> has_duplicates(range(100)) >>> False
Won't work for infinite iterators :)
A more general version that does not have to build a potentially long
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.