
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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.
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.
- Related Articles
- First occurrence of True number in Python
- Count tuples occurrence in list of tuples in Python
- Sort tuple based on occurrence of first element in Python
- Python program to get the indices of each element of one list in another list
- Last occurrence of some element in a list in Python
- How can I sort one list by values from another list in Python?
- First occurrence in the List that matches the specified conditions in C#
- C# program to remove the first occurrence of a node in a Linked List
- Python - Insert list in another list
- Count occurrence of all elements of list in a tuple in Python
- Index of first occurrence in StringCollection in C#?
- Python – Nearest occurrence between two elements in a List
- Replace first occurrence of a character in Java
- Update a list of tuples using another list in Python
- Program to count number of swaps required to change one list to another in Python?

Advertisements