Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - First occurrence of one list in another
When it is required to find the first occurrence of one list in another list, Python provides several approaches. The most efficient method uses the set data structure for fast lookups combined with the next() function for early termination.
Using next() with Set Conversion
This approach converts the second list to a set for O(1) lookup time and uses next() to return the first match ?
my_list_1 = [23, 64, 34, 77, 89, 9, 21]
my_list_2 = [64, 10, 18, 11, 0, 21]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
# Convert second list to set for faster lookup
my_list_2_set = set(my_list_2)
# Find first occurrence using next()
my_result = next((ele for ele in my_list_1 if ele in my_list_2_set), None)
print("The result is :")
print(my_result)
The first list is : [23, 64, 34, 77, 89, 9, 21] The second list is : [64, 10, 18, 11, 0, 21] The result is : 64
Using Basic Loop Approach
A simple loop-based solution that checks each element sequentially ?
my_list_1 = [23, 64, 34, 77, 89, 9, 21]
my_list_2 = [64, 10, 18, 11, 0, 21]
result = None
for element in my_list_1:
if element in my_list_2:
result = element
break
print("First common element:", result)
First common element: 64
How It Works
The second list is converted to a
setfor O(1) average lookup time instead of O(n) for list lookupsThe
next()function iterates through the generator expression and returns the first matching elementIf no match is found,
next()returns the default valueNoneThe generator expression stops at the first match, making it memory-efficient
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
next() with set |
O(n + m) | O(m) | Large lists |
| Basic loop | O(n × m) | O(1) | Small lists |
Conclusion
Use next() with set conversion for efficient lookup in large datasets. The generator expression ensures memory efficiency by stopping at the first match, while set conversion provides fast O(1) lookups.
