tup=(1,3,4,32,1,1,1)
for i in tup:
if tup.count(i) > 1:
print('REPEATED')
Asked
Active
Viewed 1.6k times
-2

Harsh Mittal
- 39
- 1
- 1
- 8
-
What output do you expect? – user2390182 Feb 04 '21 at 15:29
-
your code already works ? or do you also want to know which elements are repeated ? or at which index ? – joostblack Feb 04 '21 at 15:30
-
yes what elements are repeating i want to show them too – Harsh Mittal Feb 04 '21 at 15:31
-
You code goes through the items, and each time it sees the number 1, which is in there more than once, it prints "REPEATED" – Christopher Alcock Feb 04 '21 at 15:32
-
if you replace 'REPEATED' with `i`, you will print the number 1 four times – Christopher Alcock Feb 04 '21 at 15:33
-
Does this answer your question? [How do I find the duplicates in a list and create another list with them?](https://stackoverflow.com/questions/9835762/how-do-i-find-the-duplicates-in-a-list-and-create-another-list-with-them) – Tomerikoo Feb 04 '21 at 15:40
4 Answers
2
tup=(1,3,4,32,1,1,1,31,32,12,21,2,3)
for i in tup:
if tup.count(i) > 1:
print(i)

Harsh Mittal
- 39
- 1
- 1
- 8
0
You can use a collections.Counter
:
from collections import Counter
for k, v in Counter(tup).items():
if v > 1:
print("Repeated: {}".format(k))

user2390182
- 72,016
- 6
- 67
- 89
-
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)
in – Harsh Mittal Feb 04 '21 at 15:344 for k, v in Counter(tup).items(): 5 if v > 1: ----> 6 print("Repeated: " + k) TypeError: can only concatenate str (not "int") to str
0
var=int(input())
tup=(10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
a=list(tup)
for i in range(len(a)):
a[i]=int(a[i])
count=a.count(var)
print(var,'appears',count,'times in the tuple')
Sample Input
8
Sample Output
8 appears 4 times in the tuple
0
The Pythonic way to do this is to use collections.Counter:
>>> from collections import Counter
>>> t = (1,1,1,1,1,2,2,2,3,3,4,5,6,7,8,9)
>>> c = Counter(t)
>>> c
Counter({1: 5, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})
Counter returns a dict-like object that can be iterated through, along with other operations.

Matt Minton
- 25
- 7