Position in an list?

70,094

Solution 1

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"

Solution 2

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

Solution 3

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!

Solution 4

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

Solution 5

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]
Share:
70,094
kame
Author by

kame

I live in the area between Basel and Zürich. Nice to meet you. :)

Updated on November 14, 2020

Comments

  • kame
    kame over 3 years

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