adam tsang adam tsang - 28 days ago 7
Python Question

Python list finding with index

I was wondering how would you find the index of a element in a list if you only had part of it. For example

list = ["this", "is", "an", "example", "for", "python"]


how would you find it if you only had
"pyt"
and needed the index for python???

Answer

Straightforward for loop:

def find_starts(val, my_list):
    for i, v in my_list:
       if v.startswith(val):
           return i

(If there is no match then this returns None.) This could be made neater with a list comprehension: see this related question for more details.

Comments