How can I find where a string is in a list?

Question:

I want to set a variable to a certain value in a list. I need to find where the specific string is in the list without knowing what the contents of the list will be.
For instance:

list = ["a", "b", "c"]
valueIWantToFind = "b"

# code that finds where value is


variable = list.1

I thought of doing a for loop, but I don’t know how to get the current value of the list to compare it to the value I want to find.

Some thing like this:

for x in list:
 if(valueIWantToFind == currentValueOfList):
   variable = currentValueOfList
 else:
   continue
Asked By: AeroGlory

||

Answers:

I would use a list comprehension with an if condition

my_list = ["a", "b", "c"]

value_i_want_to_find = "b"

idx_list = [i for i, el in enumerate(my_list) if el == value_i_want_to_find]

You’ll have a list of indices where the element equals value_i_want_to_find.

Answered By: Seb

"I need to find where the specific string is in the list without knowing what the contents of the list will be".

For this you would use the index() function of a list but also take into account that if what you’re looking for doesn’t exist you’ll get an exception.

For example:

list_ = ['a', 'b', 'c']
try:
  idx = list_.index('b')
  print(f'Found at index {idx}')
  idx = list_.index('z')
  print(f'Found at index {idx}') # this won't happen
except ValueError:
  print('Not found') # this will happen when we search for 'z'

Output:

Found at index 1
Not found
Answered By: CtrlZ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.