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
- Function Definition (
def common_item(a, b):
):- This line defines a function named
common_item
that takes two parameters,a
andb
, which are expected to be lists.
- This line defines a function named
- Convert Lists to Sets (
s1 = set(a)
ands2 = set(b)
):s1
is created by converting lista
into a set. This removes any duplicate elements froma
.s2
is created by converting listb
into a set. This removes any duplicate elements fromb
.
- Check for Intersection (
if(s1.intersection(s2)):
):- The
intersection
method finds common elements between the two setss1
ands2
. - If there are any common elements, the intersection will be a non-empty set, which evaluates to
True
.
- The
- 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.
- If the intersection is non-empty,
- Input and Function Call:
- The user is prompted to input two lists using
eval(input('Enter Your 1st list items in Square bracket:'))
andeval(input('Enter Your 2nd list items in Square bracket:'))
. - These inputs are stored in variables
l1
andl2
. - The
common_item
function is called withl1
andl2
as arguments, and the result is printed.
- The user is prompted to input two lists using
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]
andl2
will be[3, 4, 5]
.s1
will be{1, 2, 3}
ands2
will be{3, 4, 5}
.- The intersection of
s1
ands2
will be{3}
, which is non-empty. - Thus, the function will return
True
and the output will beTrue
.