When it is required to find the first occurrence of one list in another list, the ‘set’ attribute and the ‘next’ method is used.
Example
Below is a demonstration of the same
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) my_list_2 = set(my_list_2) my_result = next((ele for ele in my_list_1 if ele in my_list_2), None) print("The result is :") print(my_result)
Output
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
Explanation
Two lists are defined, and are displayed on the console.
The second list is converted to a set.
This way, all the unique elements are retained.
The duplicate elements would be eliminated.
The ‘next’ method is used to iterate to the next value by iterating through the first and second list.
This output is assigned to a variable.
This is displayed as output on the console.