- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - First occurrence of one list in another
When it is required to find the first occurrence of one list in another list, the ‘set’ attribute and the ‘next’ method is used.
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)
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
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.
- First occurrence of True number in Python
- Python program to get the indices of each element of one list in another list
- Sort tuple based on occurrence of first element in Python
- Count tuples occurrence in list of tuples in Python
- Index of first occurrence in StringCollection in C#?
- Replace first occurrence of a character in Java
- Last occurrence of some element in a list in Python
- Python - Insert list in another list
- C# program to remove the first occurrence of a node in a Linked List
- First occurrence in the List that matches the specified conditions in C#
- Count occurrence of all elements of list in a tuple in Python
- Removing first occurrence of object from Collection in C#
- Program to count number of swaps required to change one list to another in Python?
- Update a list of tuples using another list in Python
- Add one Python string to another