How to Efficiently Determine Sublist Presence in a Python List?

Linda Hamilton
Release: 2024-10-26 18:01:03
Original
324 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template