Chen Xu
Chen Xu

Reputation: 352

Find the position of sublist in a list in python

For example, I have two list x and y in Python. Supposing x = [0,1,2,3,4,5,6,7] and y = [3,4,5], it is clear that y is a sublist of x and the position of sublist y in x is 3. In other words,I'm trying to get a function that judges whether a list is a sublist in another list. If so,I would like to figure out the position of the sublist as well.

I don't know if there has any off-the-shelf function I can use. If not, does anyone have an idea of how I can achieve it using some effective method.

Thanks for any help in advance!

Upvotes: 1

Views: 1335

Answers (1)

SuperNova
SuperNova

Reputation: 27466

x = [0,1,2,3,4,5,6,7]
y = [3,4,5]

occ = [i for i, a in enumerate(x) if a == y[0]]

for b in occ:
      if x[b:b+len(y)] == y:
           print 'YES-- SUBLIST at : ', b
           break
      if len(occ)-1 ==  occ.index(b):
           print 'NO SUBLIST'
           break

Upvotes: 1

Related Questions