This tutorial will discuss about a unique way to check if any element of list is in another list in Python.
Suppose we have two lists,
strList1 = ['Sample', 'Like', 'This'] strList2 = ['That', 'Where', 'Why', 'This', 'Now']
Now we want to check if any element from first list i.e. strList1
exists in the second list i.e. strList2
or not.
For this, we can iterate over all the elements of first list, and during iteration, for each element check if it exists in the second list or not. If yes, then break the loop, and mark that an element from first list exists in the second list. We have created a function for this,
def is_overlapped(firstList, secondList): ''' Returns True, if any element from first list exists in the second List.''' result = False for item in firstList: if item in secondList: result = True return result
It accepts two lists as arguments, and retruns True, if any element from first list exists in the second List. Inside the function we will loop over all the elements of first list and check for their existence in the second list.
Frequently Asked:
Let’s see some examples,
Example 1
In this example, the first list had an element that exists in the second list.
Let’s see the complete example,
def is_overlapped(firstList, secondList): ''' Returns True, if any element from first list exists in the second List.''' result = False for item in firstList: if item in secondList: result = True return result # Example 1 strList1 = ['Sample', 'Like', 'This'] strList2 = ['That', 'Where', 'Why', 'This', 'Now'] if is_overlapped(strList1, strList2): print('Yes, an element of first List is in second List') else: print('None of the element from first List is not in second List')
Output
Latest Python - Video Tutorial
Yes, an element of first List is in second List
Example 2
In this example, the first list and second list has no common elements.
Let’s see the complete example,
def is_overlapped(firstList, secondList): ''' Returns True, if any element from first list exists in the second List.''' result = False for item in firstList: if item in secondList: result = True return result strList1 = ['Sample', 'Like', 'Text'] strList2 = ['That', 'Where', 'Why', 'This', 'Now'] if is_overlapped(strList1, strList2): print('Yes, an element of first List is in second List') else: print('None of the element from first List is not in second List')
Output
None of the element from first List is not in second List
Summary
We learned how to check if any element of a List is present in another List in Python. Thanks.
Latest Video Tutorials