Open In App

Python – First Occurrence of One List in Another

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
2

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)

Output
2

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)

Output
2

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)

Output
2

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) 

Output
2

Explanation:

  • A deque is initialized with the first len(b) elements.
  • The deque slides over a, checking for a match with b.


Next Article
Practice Tags :

Similar Reads