Python function that takes two lists and returns True if they have at least one common item

Write a Python function that takes two lists and returns True if they have at least one common item.

def common_item(a, b):
    s1 = set(a)
    s2 = set(b)
    if s1.intersection(s2):
        return True
    else:
        return False

l1 = eval(input('Enter Your 1st list items in Square bracket:'))
l2 = eval(input('Enter Your 2nd list items in Square bracket:'))
print(common_item(l1, l2))
Output: 
Enter Your 1st list items in Square bracket: [1, 2, 3]
Enter Your 2nd list items in Square bracket: [3, 4, 5]

Explanation

  1. Function Definition (def common_item(a, b):):
    • This line defines a function named common_item that takes two parameters, a and b, which are expected to be lists.
  2. Convert Lists to Sets (s1 = set(a) and s2 = set(b)):
    • s1 is created by converting list a into a set. This removes any duplicate elements from a.
    • s2 is created by converting list b into a set. This removes any duplicate elements from b.
  3. Check for Intersection (if(s1.intersection(s2)):):
    • The intersection method finds common elements between the two sets s1 and s2.
    • If there are any common elements, the intersection will be a non-empty set, which evaluates to True.
  4. Return Result:
    • If the intersection is non-empty, True is returned.
    • If the intersection is empty (i.e., there are no common elements), False is returned.
  5. Input and Function Call:
    • The user is prompted to input two lists using eval(input('Enter Your 1st list items in Square bracket:')) and eval(input('Enter Your 2nd list items in Square bracket:')).
    • These inputs are stored in variables l1 and l2.
    • The common_item function is called with l1 and l2 as arguments, and the result is printed.

Example

Let’s go through an example where the user inputs two lists. Suppose the user inputs the following:

mathematicaCopy codeEnter Your 1st list items in Square bracket: [1, 2, 3]
Enter Your 2nd list items in Square bracket: [3, 4, 5]

The code execution will be as follows:

  • l1 will be [1, 2, 3] and l2 will be [3, 4, 5].
  • s1 will be {1, 2, 3} and s2 will be {3, 4, 5}.
  • The intersection of s1 and s2 will be {3}, which is non-empty.
  • Thus, the function will return True and the output will be True.

Leave a Reply

Your email address will not be published. Required fields are marked *