python search list for string code example

Example 1: python return first list element that contains substring

# Example usage:
your_list = ['The answer to', 'the ultimate question', 'of life', 
     'the universe', 'and everything', 'is 42']

[idx for idx, elem in enumerate(your_list) if 'universe' in elem][0]
--> 3 # The 0-based index of the first list element containing "universe"

Example 2: check if list contains string python

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

Example 3: python find string in list

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

isBInList = "b" in list1 # True

Tags:

Vb Example