Python - First Occurrence of One List in Another
Last Updated :
31 Jan, 2025
We are given two lists, and our task is to find the first occurrence of the second list as a contiguous subsequence in the first list. If the second list appears as a subsequence inside the first list, we return the starting index of its first occurrence; otherwise, we return -1. For example, if a = [1, 2, 3, 4, 5, 6] and b = [3, 4, 5], the result should be 2 because [3, 4, 5] starts at index 2 in a. Let's discuss different methods to do this in Python.
Using next() with Generator Expression
A generator expression with next() provides an efficient way to find the first match without iterating the entire list.
Python
# Initializing lists
a = [1, 2, 3, 4, 5, 6]
b = [3, 4, 5]
# Finding first occurrence using next()
index = next((i for i in range(len(a) - len(b) + 1) if a[i:i + len(b)] == b), -1)
print(index)
Explanation:
- The generator expression checks each possible starting index in a.
- next() returns the first valid index and avoids unnecessary iterations.
- If no match is found, -1 is returned.
Let's explore some more ways to find the first occurrence of one list in another.
Using Slicing and Loop
We can iterate through the first list and check for the occurrence of the second list using slicing.
Python
# Initializing lists
a = [1, 2, 3, 4, 5, 6]
b = [3, 4, 5]
# Finding first occurrence
index = -1
for i in range(len(a) - len(b) + 1):
if a[i:i + len(b)] == b:
index = i
break
print(index)
Explanation:
- We iterate through a while ensuring enough elements remain to match b.
- We use slicing a[i:i + len(b)] to check if the current sublist matches b.
- The loop breaks at the first match and returns the starting index.
Using str() Conversion
By converting lists to strings, we can use substring searching methods for efficient lookup.
Python
# Initializing lists
a = [1, 2, 3, 4, 5, 6]
b = [3, 4, 5]
# Converting lists to strings
a_str = ' '.join(map(str, a))
b_str = ' '.join(map(str, b))
# Finding first occurrence
index = a_str.find(b_str)
index = -1 if index == -1 else len(a_str[:index].split())
print(index)
Explanation:
- We convert both lists to space-separated strings.
- find() locates the first occurrence of b in a.
- We count the number of elements before the match to get the correct index.
Using re
Regular expressions allow us to search for a list pattern in another list.
Python
import re
# Initializing lists
a = [1, 2, 3, 4, 5, 6]
b = [3, 4, 5]
# Converting lists to string patterns
a_str = ' '.join(map(str, a))
b_str = ' '.join(map(str, b))
# Using regex search
match = re.search(r'\b' + re.escape(b_str) + r'\b', a_str)
index = -1 if not match else len(a_str[:match.start()].split())
print(index)
Explanation:
- Lists are converted to space-separated strings.
- re.search() finds the first occurrence of b in a.
- We count the words before the match to determine the index.
Using collections.deque()
Using a deque allows us to efficiently compare elements while sliding over the list.
Python
from collections import deque
# Initializing lists
a = [1, 2, 3, 4, 5, 6]
b = [3, 4, 5]
# Creating a deque for comparison
window = deque(a[:len(b)], maxlen=len(b))
index = 0 if list(window) == b else -1
for i in range(len(b), len(a)):
window.append(a[i])
if list(window) == b:
index = i - len(b) + 1
break
print(index)
Explanation:
- A deque is initialized with the first len(b) elements.
- The deque slides over a, checking for a match with b.
Similar Reads
Python - Sum of each List element occurrence in another Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can
6 min read
Python - First Occurrence of True number We are given a list of True and False we need to find first occurrence of True. For example we are having a list a = [False, False, True, False, True] so we need to return first occurrence of True so that output should be 2 in this case.Using index()index() method in Python returns index of first oc
2 min read
Python | Intersection of multiple lists Given two list of lists, write a Python program to find the intersection between the given two lists. Examples: Input : lst1 = [['a', 'c'], ['d', 'e']] lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']] Output : [['a', 'c'], ['d', 'e']] Input : lst1 = [[1, 5, 7], [2, 3], [6, 9], [4, 8]] lst2 = [[9, 3], [2,
5 min read
Insert list in another list - Python We are given two lists, and our task is to insert the elements of the second list into the first list at a specific position. For example, given the lists a = [1, 2, 3, 4] and b = [5, 6], we want to insert list 'b' into 'a' at a certain position, resulting in the combined list a = [1, 2, 5, 6, 3, 4]
3 min read
Check if a Nested List is a Subset of Another Nested List - Python The task is to check if all sublists in one nested list are present in another nested list. This is done by verifying whether each sublist in the second list exists in the first list.For example, given list1 = [[2, 3, 1], [4, 5], [6, 8]] and list2 = [[4, 5], [6, 8]], we check if both [4, 5] and [6,
4 min read