Exercise 30

Write a Python algorithm as a function that takes two lists as input arguments and returns a boolean value indicating whether or not they have at least one common element.

Solution

def has_common_element(list1, list2):
    """
    Check if two lists have at least one common element.
    """
    for item1 in list1:
        for item2 in list2:
            if item1 == item2:
                return True
    return False
# You can call this function with two lists, for example:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
print(has_common_element(list1, list2)) # prints True

list3 = [10, 11, 12]
list4 = [13, 14, 15]
print(has_common_element(list3, list4)) # prints False





Explanation:

  1. This function iterates through each item: n the first list and compares it with every item in the second list.
  2. If a match is found: it returns True.
  3. If the function found no match: after has checked all pairs of items, the function returns False.
  4. In the first example: the function returns True because both lists have the common value 5.
  5. In the second example: the function returns False because there are no common values between the two lists.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 30: check if two lists have common values in python”

Leave a Reply