Home > database >  If any of 'words' in list, print the index(s) of list with the word(s) (python)
If any of 'words' in list, print the index(s) of list with the word(s) (python)

Time:07-02

#input list
lst = ['abc', 'def', 'ghi','python', 'pool']


if any(word in lst for word in ('def', 'kok', 'python')):
   print(lst.index(word))
else:
   print("string is not present")

Since the word 'def' and 'python' is in list at list[1] and list[3]. the output should be:

1

3

But I get.. NameError: name 'word' is not define. How would I make it print the desired results?

CodePudding user response:

The any statement returns a boolean value only, you can't use what was given to it anymore. Then you can understand that lst.index(word) would give one value, not : all the indexes of words that are present

Compute the list of indexes for word that are present, then print them if there is any, or print the else string

lst = ['abc', 'def', 'ghi', 'python', 'pool']

indexes = [lst.index(word) for word in ('def', 'kok', 'python') if word in lst]

if indexes:  
    print(*indexes)
else:
    print("string is not present")

CodePudding user response:

Try without using "any" function:

lst = ['abc', 'def', 'ghi','python', 'pool']

for word in ('def', 'kok', 'python'):
    if word in lst:
        print(lst.index(word))
    else:
        print("string is not present")

CodePudding user response:

You can avoid using a comprehension with a for loop:

lst = ['abc', 'def', 'ghi','python', 'pool']

out = []
for word in ('def', 'kok', 'python'):
  if word in lst:
    out.append(word)
    print(f"string {word} is present on index {lst.index(word)}")
  else:
    print(f"string {word} is not present")

Output:

string def is present on index 1
string kok is not present
string python is present on index 3
  • Related