0
my_list=raw_input('Please enter a list of items (seperated by comma): ')
my_list=my_list.split()
my_list.sort()

print "List statistics: "
print ""

for x in set(my_list):
    z=my_list.count(x)

if z>1:
    print x, "is repeated", z, "times."
else:
    print x, "is repeated", z, "time."

The output only prints one of the items in the list. I need to sort the list (dog, cat, bird, dog, dog) to count how many items are in the list, such as:

bird is repeated 1 time. cat is repeated 1 time. dog is repeated 3 times.

The problem is that it only outputs 1 item:

bird is repeated 1 time.

2

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help! Although I am still having issues. It is now not sorting the list alphabetically and when it prints if there is more than one item it repeats, i.e. (dog, cat, bird, dog, dog): dog is repeated 3 times. cat is repeated 1 time. bird is repeated 1 time. dog is repeated 3 times. dog is repeated 3 times. THANK YOU!
Sir, that is fantastic! Thank you so much with your help it has really helped me to better understand what I am doing!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.