Sundrah
Sundrah

Reputation: 865

Python - How to return the indice value of a list?

Currently I have

 for element in initialString:
    if element == word:
      print(element.index(initialString))

where initialString is a list and word is a called variable.

However, it is returning a TypeError telling me that it cannot convert a 'list' object to str implicity.

Upvotes: 0

Views: 168

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You'd use initialString.index(element) (so reversed) instead; the list can tell you what index it has element stored in; element has no knowledge of the list.

You should really use enumerate() here however, to add indices to the loop:

 for i, element in enumerate(initialString):
     if element == word:
         print(i)

If all you wanted to know was the index of word, however, it is simpler still to just use:

print(initialString.index(word))

Upvotes: 2

Related Questions