-2

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???

adam tsang
  • 15
  • 3
  • 4
    It depends how you want a match to be decided. For example, would `is` match "is" or "this" or both? – user2699 Nov 07 '16 at 20:30
  • 1
    as @user2699 mentioned, what kind of result are you expecting: only the index of the first matched element or list of indexes by all matches? – RomanPerekhrest Nov 07 '16 at 20:38

4 Answers4

1

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.

Community
  • 1
  • 1
Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
1

As the question is not 100% clear i assume you want to find all items that include the specified string.

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

val = 'is'

def find_in_list(alist, val):
    res = []
    for e, v in enumerate(alist):
       if val in v:
           res.append(e)
    return res

find_in_list(alist, val)
Richy
  • 380
  • 2
  • 10
  • Thanks for the help however I was thinking this. ["Bob smith","Garry Taylor"] how would I find the index if I just gave it Bob??? Thx – adam tsang Nov 07 '16 at 21:11
  • alist = ["Bob smith","Garry Taylor"] val = 'Bob' – Richy Nov 07 '16 at 21:18
  • dear @Richy this doesn't work as bob is not the whole element any way to get around it??? – adam tsang Nov 08 '16 at 19:01
  • @adamtsang this works fine for me, the check is `if val in v` so Bob has just to be in Bob smith, and that's the case. https://docs.python.org/3/reference/expressions.html#in – Richy Nov 08 '16 at 22:15
0

You have to work with a solution that work when some element are similar (for example ["foo", "asd", "foobar"] and you have "foo" what would be detected as a correct element?)

The given function will return a list of indexes, which were identified as a correct element.

def find(foo, list):
   #Find similar elements
   similarElements = [e for e in list if foo in e]
   #Find their indexes
   indexes = [similarElements.index(i) for i in similarElements]
   return indexes

This solution isn't the fastest way, but an easy and understandable.

Fontinalis
  • 550
  • 1
  • 7
  • 21
0
>>> list = ["this", "is", "an", "example", "for", "python"]
>>> word = "python"
>>> y = [i for i,j in enumerate(list) if j == word]
>>> y
[5]

However, this is for the whole word, try this aswell.

>>> word = "py"
>>> for w in list:
...     if word in w:
...             sus.append(w)
...             print(sus)
...
['python']
Simeon Aleksov
  • 1,275
  • 1
  • 13
  • 25