Check If Two Lists Have At-least One Element Common In Python
Chapter:
Python
Last Updated:
17-05-2023 15:25:08 UTC
Program:
/* ............... START ............... */
def have_common_element(list1, list2):
for element in list1:
if element in list2:
return True
return False
# Example usage
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
has_common = have_common_element(list1, list2)
if has_common:
print("The lists have at least one common element.")
else:
print("The lists do not have any common elements.")
/* ............... END ............... */
Output
If list1 and list2 have at least one common element:
Output : The lists have at least one common element.
If list1 and list2 do not have any common element:
Output : The lists do not have any common elements.
Notes:
-
In this program, the have_common_element function takes two lists (list1 and list2) as arguments. It uses a for loop to iterate over each element in list1. For each element, it checks if that element is present in list2 using the in operator. If a common element is found, it immediately returns True. If the loop completes without finding any common element, it returns False.
- The program demonstrates the usage of the function by checking if list1 and list2 have at least one common element. Based on the result, it prints the appropriate message.
Tags
Python check if two sets have common elements #Check If Two Lists Have At-least One Element Common In Python #Python check if two sets have common elements example