15

I will check if a word exists in a list. How can I show the position of this word?

kame
  • 20,848
  • 33
  • 104
  • 159
  • 3
    You do it by searching for folks who already asked this question and reading the answers already presented here. – S.Lott Nov 02 '10 at 20:56
  • 1
    Either http://stackoverflow.com/questions/364621/python-get-position-in-list or http://stackoverflow.com/questions/3989016/how-to-find-positions-of-the-list-maximum will answer your question. – S.Lott Nov 02 '10 at 20:57
  • Possible duplicate of [How to get item's position in a list?](https://stackoverflow.com/questions/364621/how-to-get-items-position-in-a-list) – Stephan Weinhold Feb 06 '18 at 07:05

7 Answers7

29
list = ["word1", "word2", "word3"]
try:
   print list.index("word1")
except ValueError:
   print "word1 not in list."

This piece of code will print 0, because that's the index of the first occurrence of "word1"

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Personally, I think the exception approach is valid iff you expect the word to be in the array, but maybe that's just me. Otherwise, you could test for the presence of the word in the list before finding its index, as shown by jleedev. – Lee-Man Nov 02 '10 at 20:21
  • 1
    @Lee-Man he asked for a function which would return the index of a value in a list, and I gave that to him, with all use cases. I agree that jleedev's solution is more comfortable, but I tried to provide all use cases for `.index` – Gabi Purcaru Nov 02 '10 at 20:25
  • IMHO using `.index()` inside a `try/except` is the most efficient approach since it only searches for a match once, and is totally "Pythonic" in the sense that it employs the [EAFP ](http://docs.python.org/glossary.html#term-eafp) (Easier to Ask Forgiveness than Permission) style of programming. – martineau Nov 02 '10 at 22:13
  • @Lee-Man: Ignoring double lookups, if exceptional cases are rare, then code using exceptions will have better average performance than the alternative. – martineau Nov 02 '10 at 22:23
3

To check if an object is in a list, use the in operator:

>>> words = ['a', 'list', 'of', 'words']
>>> 'of' in words
True
>>> 'eggs' in words
False

Use the index method of a list to find out where in the list, but be prepared to handle the exception:

>>> words.index('of')
2
>>> words.index('eggs')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'eggs' is not in list
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
2

The following code:

sentence=["I","am","a","boy","i","am","a","girl"]
word="am"
if word in sentence:
    print( word, " is in the sentence")
    for i, j in enumerate(sentence):
        if j == word:
            print("'"+word+"'","is in position",i+1)

would produce this output:

"am" is in position 1
"am" is in position 5

This is because in python the indexing starts at 0

Hope this helped!

Marko Popovic
  • 3,999
  • 3
  • 22
  • 37
2

you can use ['hello', 'world'].index('world')

Antoine Pelisse
  • 12,871
  • 4
  • 34
  • 34
2

using enumeration - to find all occurences of given string in list

listEx=['the','tiger','the','rabit','the','the']
print([index for index,ele in enumerate(listEx) if ele=='the'])

output

[0, 2, 4, 5]
SRG
  • 345
  • 1
  • 9
0

Sounds like you want indexof. From here:

operator.indexOf(a, b)¶ Return the index of the first of occurrence of b in a.

Doug T.
  • 64,223
  • 27
  • 138
  • 202
0

Assuming the word is named for example "Monday":

You will need a list as your initial database:

myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]

Then you need to loop through your list one by one to the end using for, next(), iter() and len() function:

myIter = iter(myList)
for i in range(0, len(myList)):
next_item = next(myIter)

Now while looping, you need to check if the wanted word exists and wherever it exists, print it:

if next_item == "Monday":
    print(i)

Altogether:

myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]
myIter = iter(myList)
for i in range(0, len(myList)):
    next_item = next(myIter)
    if next_item == "Monday":
        print(i)

Since there are two Mondays in this list, the result for this example will be: 0 2

Feri
  • 230
  • 4
  • 11