Chunwing Ng
Chunwing Ng

Reputation: 13

How do I display an item which is in the list multiple times?

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

Answers (3)

twalberg
twalberg

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

roman
roman

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

Steve Jessop
Steve Jessop

Reputation: 279255

all_indexes = [idx for idx, value in enumerate(dlist) if value == y]

Upvotes: 2

Related Questions