1

Given

listEx = ['cat', 'dog', 'cat', 'turtle', 'apple', 'bird', 'bird']

for i in listEx:
    if listEx.count(i) > 1:
        print "this item appears more than once", i
    else:
        print "this item appears only once", i

I want it to print that cat and bird appear more than once (or just produce ['cat', 'bird']). How can I do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
phales15
  • 465
  • 4
  • 7
  • 18

5 Answers5

7

The collections.Counter tool makes this sort of task really easy:

>>> from collections import Counter
>>> listEx = ['cat', 'dog', 'cat', 'turtle', 'apple', 'bird', 'bird']
>>> [k for k, cnt in Counter(listEx).items() if cnt > 1]
['bird', 'cat']
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
6
>>> [v for v, r in itertools.groupby(sorted(listEx)) if len(list(r)) > 1]
['bird', 'cat']
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

All previous answers are great. I just wanted to point out, that you could also simply use a dictionary to count your items:

>>> listEx = ['cat', 'dog', 'cat', 'turtle', 'apple', 'bird', 'bird']
>>> d = dict()
>>> for v in listEx: d[v] = d[v] + 1 if v in d else 1
...
>>> d
{'turtle': 1, 'bird': 2, 'apple': 1, 'dog': 1, 'cat': 2}
>>> for v in d:
...     if d[v] > 1:
...             print v
...
bird
cat
>>>
MarcoS
  • 13,386
  • 7
  • 42
  • 63
0

You can also use a collections.defaultdict to do the counting:

from collections import defaultdict

animals = ["cat", "dog", "cat", "turtle", "apple", "bird", "bird"]

animal_counts = defaultdict(int)
for animal in animals:
    animal_counts[animal] += 1

print([animal for animal, count in animal_counts.items() if count > 1])
# ['cat', 'bird']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
-1
[word for word in set(listEx) if listEx.count(word) > 1]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153