0

I want to check if the list1 is a sublist to list2 in the same order. The most important thing is that objects must be in the same sequence.

For Examples, these are two list:

list1=[1,2,3]
list2=[8,9,1,2,3,6,5]

which should give me True when checked,because objects 1,2 nad 3 are in the same sequence in list1 as in list2.

In other side:

list1=[2,3,1]
list2=[1,2,3]

This should give me False as the order is not the same in list2.

So far I have made that:

def sublist(list1,list2):
    s1=" ".join(str(i) for i in list1)
    s2=" ".join(str(i) for i in list2)
    if s1 in s2:
        return True
    else:
        return False
Red
  • 26,798
  • 7
  • 36
  • 58
cool guy
  • 1
  • 1

3 Answers3

0

A straight forward solution would be

def sublist(list1, list2):
    for i in range(len(list2)-len(list1)):
        if list2[i:i+len(list1)] == list1:
            return i, True
        else:
            return -1, False

returning also the index of the potential match or -1 otherwise.

ctenar
  • 718
  • 5
  • 24
  • You can return anything else that is supposed to indicate the list is not present as a sublist, it just should not be anything that could be mixed up with a valid index. Using -1 for this is not too uncommon. – ctenar Jun 18 '20 at 13:31
0
list1=[1,2,3]
list2=[8,9,1,2,3,6,5]

def list_in_list(l1,l2):
    return_val = False
    for i in range(len(list2)):
        if list1 == list2[i:i+len(list1)]:
            return_val=True
        continue
    return return_val

list_in_list(list1,list2)
True
BERA
  • 1,345
  • 3
  • 16
  • 36
  • SO doesn't tolerate code only answers. – Red Jun 18 '20 at 13:26
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Abhishek Bhagate Jun 18 '20 at 19:03
0

Your code is working fine

Indentation was wrong other-wise even for the case given it gives correct answer

list1=[2,3,1]
list2=[1,2,3]
def sublist(list1,list2):
    s1=" ".join(str(i) for i in list1)
    s2=" ".join(str(i) for i in list2)
    if s1 in s2:
        return True
    else:
        return False
sublist(list1,list2)

enter image description here

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22