let's say i have a list of things, like:

[bread, cookies, cake, chocolate, bread]

how can I make loop that will, in each iteration, create a variable with the name of the item in the list?

basically, i want to be able to count the times each item appears in the list, how can i do this?

basically, i want to be able to count the times each item appears in the list, how can i do this?

x=0
list1= [bread, cookies, cake, chocolate, bread]
list2=[]
for i in list1:
    if not i in list2:
        list2.append(i)
        x += 1
print x

redyugi: your code gives x as 4 not 2.

try this:

wordlist = ["bread", "cookies", "cake", "chocolate", "bread"]
d = {}
for word in wordlist:
  d[word] = d.get[word,0) + 1

And to see what the outcome is:

for i in d.keys():
  print i,d[i]

My results:

>>> wordlist = ["bread","cookies","cake","chocolate","bread"]
>>> d = {}
>>> for word in wordlist:
...   d[word] = d.get(word,0) +1
...
>>> for i in d.keys():
...   print i,d[i]
...
cake 1
cookies 1
chocolate 1
bread 2

Edited 6 Years Ago by Tech B: n/a

redyugi you code dos the same as set()

print len(set(["bread","cookies","cake","chocolate","bread"]))
4

That only remove duplicate in a list.
For count with set() this is a solution.

wordlist = ["bread", "cookies", "cake", "chocolate", "bread"]
for item in set(wordlist):
    print '%s %s' % (item,wordlist.count(item))

'''Out-->
cake 1
cookies 1
chocolate 1
bread 2
'''

Edited 6 Years Ago by snippsat: n/a

This article has been dead for over six months. Start a new discussion instead.