You need to move your test for z
inside the loop:
for x in sorted(set(my_list)):
z=my_list.count(x)
if z>1:
print x, "is repeated", z, "times."
else:
print x, "is repeated", z, "time."
or, simplified a little:
for word in sorted(set(my_list)):
count = my_list.count(word)
print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '')
Demo:
>>> my_list = ['dog', 'cat', 'bird', 'dog', 'dog']
>>> for word in sorted(set(my_list)):
... count = my_list.count(word)
... print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '')
...
bird is repeated 1 time.
cat is repeated 1 time.
dog is repeated 3 times.
You could also use a collections.Counter()
object to do the counting for you, it has a .most_common()
method to return results sorted on frequency:
>>> from collections import Counter
>>> for word, count in Counter(my_list).most_common():
... print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '')
...
dog is repeated 3 times.
bird is repeated 1 time.
cat is repeated 1 time.