Sarah Pierson Sarah Pierson - 3 months ago 13
Python Question

Boolean expression for if list is within other list

What is a efficient way to check if a list is within another list? Something like:

[2,3] in [1,2,3,4] #evaluates True
[1,5,4] in [5,1,5,4] #evaluates True
[1,2] in [4,3,2,1] #evaluates False


Order within the list matters.

Answer
def check_ordered_sublist_in_list(sub_list, main_list):
    sub_list = np.array(sub_list)
    main_list = np.array(main_list)
    return any(all(main_list[n:(n + len(sub_list))] == sub_list) 
               for n in range(0, len(main_list) - len(sub_list) + 1))

>>> check_ordered_sublist_in_list([2, 3], [1, 2, 3, 4])
True

>>> check_ordered_sublist_in_list([1, 5, 4], [5, 1, 5, 4])
True

>>> check_ordered_sublist_in_list([1, 2], [4, 3, 2, 1])
False

This converts the lists to numpy arrays (for computational efficiency) and then uses slicing to check if the sub_list is contained within the slice. Any success returns True.

Comments