1

Here's the solution to find y list index in x big list

def getsubidx(x, y):
    l1, l2 = len(x), len(y)
    for i in range(l1):
        if x[i:i+l2] == y:
            return i

Is it possible to transform this to oneliner using itertools, filter or something else?

user2229336
  • 169
  • 1
  • 7

3 Answers3

1
def getsubidx(x, y):
    return next(i for i in range(len(x)) if x[i:i+len(y)] == y)

You may want an error to be raised if no match, if you don't you can return -1

return next((i for i in range(len(x)) if x[i:i+len(y)] == y), -1)
jamylak
  • 128,818
  • 30
  • 231
  • 230
0
def getsubidx(x, y):
    l1, l2 = len(x), len(y)
    for i in range(l1-l2):   here it should be l1-l2
        if x[i:i+l2] == y:        here you may get list out of index
            return i

one liner:

def getsubidx(x, y):
    return [i for i in range(len(x)-len(y)) if x[i:i+len(y)] == y]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

Is it possible to transform this to oneliner using itertools, filter or something else?

Here's "somethng else", you could use index(subseq, seq) function:

index_of_y_in_x = index(y, x) 
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670