Reputation: 13
It always gives me the first time it appears with .index()
. I want index to equal the places of the list. For example, This word appears in the places, 0,4
. If the user typed chicken that would be the output.
dlist = ["chicken","potato","python","hammer","chicken","potato","hammer","hammer","potato"]
x=None
while x != "":
print ("\nPush enter to exit")
x = input("\nGive me a word from this list: Chicken, Potato, Python, or Hammer")
y = x.lower()
if y in dlist:
count = dlist.count(y)
index = dlist.index(y)
print ("\nThis word appears",count,"times.")
print ("\nThis word appears in the places",index)
elif y=="":
print ("\nGood Bye")
else:
print ("\nInvalid Word or Number")
Upvotes: 0
Views: 70
Reputation: 62379
Something along these lines should work:
index_list = [i for i in xrange(len(dlist)) if dlist[i] == "hammer"]
That gives the list [3, 6, 7]
in your example...
Upvotes: 0
Reputation: 117370
you can use
r = [i for i, w in enumerate(dlist) if w == y]
print ("\nThis word appears",len(r),"times.")
print ("\nThis word appears in the places", r)
instead of
count = dlist.count(y)
index = dlist.index(y)
print ("\nThis word appears",count,"times.")
print ("\nThis word appears in the places",index)
Upvotes: 3
Reputation: 279255
all_indexes = [idx for idx, value in enumerate(dlist) if value == y]
Upvotes: 2