Home  >  Article  >  Backend Development  >  How to Efficiently Determine Sublist Presence in a Python List?

How to Efficiently Determine Sublist Presence in a Python List?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 18:01:03252browse

How to Efficiently Determine Sublist Presence in a Python List?

Determining Sublist Presence in a Python List

To check whether a sublist exists within a larger list, one can utilize the power of functional programming in Python. Here's a concise function that accomplishes this:

<code class="python">def contains_sublist(lst, sublst):
    n = len(sublst)
    return any((sublst == lst[i:i+n]) for i in range(len(lst)-n+1))</code>

The function works by iterating through the larger list lst, starting at index i, and comparing a slice of length n (the length of the sublist) with the sublist sublst. If any of these slices match sublst, the function returns True. Otherwise, it returns False.

Consider the following examples:

<code class="python">lst1 = [1,0,1,1,1,0,0]
lst2 = [1,0,1,0,1,0,1]

sublistExists(lst1, [1,1,1]) == True
sublistExists(lst2, [1,1,1]) == False</code>

The function operates in O(m*n) time complexity, where m is the length of the larger list and n is the length of the sublist. It leverages the any() function to efficiently exit upon the first match, ensuring computational efficiency.

The above is the detailed content of How to Efficiently Determine Sublist Presence in a Python List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn