Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

List xor

Define a function named list_xor. Your function should take three parameters: n, list1 and list2.

Your function must return whether n is exclusively in list1 or list2.

In other words, if n is in both lists or in none of the lists, return False. If n is in only one of the lists, return True.

For example:

list_xor(1, [1, 2, 3], [4, 5, 6]) == True
list_xor(1, [0, 2, 3], [1, 5, 6]) == True
list_xor(1, [1, 2, 3], [1, 5, 6]) == False
list_xor(1, [0, 0, 0], [4, 5, 6]) == False



==== SOLUTION ====

“`python
def list_xor(n, list1, list2):
        return (n in list1) != (n in list2)

# Test cases
print(list_xor(1, [1, 2, 3], [4, 5, 6])) # Output: True
print(list_xor(1, [0, 2, 3], [1, 5, 6])) # Output: True
print(list_xor(1, [1, 2, 3], [1, 5, 6])) # Output: False
print(list_xor(1, [0, 0, 0], [4, 5, 6])) # Output: False
“`

 

Explanation:

1. `def list_xor(n, list1, list2):`: This line defines a function named `list_xor` that takes three parameters: `n`, `list1`, and `list2`.

2. `(n in list1)`: This expression checks if `n` is present in `list1`.

3. `(n in list2)`: This expression checks if `n` is present in `list2`.

4. `return (n in list1) != (n in list2)`: This line returns `True` if `n` is exclusively in either `list1` or `list2`, but not in both. It does so by checking if `n` is present in one list but not the other using the inequality (`!=`) operator.

This function returns `True` if `n` is exclusively in one of the lists and `False` otherwise, as specified.


Join the conversation