Search code examples
pythonpython-3.xliststring-comparison

How to compare two lists in python and write the similar index values in one list and non similar values in another list


consider two lists a=[1,2,3], b=[1,4,5].The Code should print the similar values c=[1] and the Code should print d=[2,3,4,5] which shows different values

--completed --


Solution

  • A simple and alternative solution using list comprehension and logical operators is given below:

    a = [1,2,3]
    b = [1,4,5]
    
    print([x for x in a if x in b])
    print([x for x in set(a+b) if (x in a) ^ (x in b)])
    

    A solution with set operation has already been given by other person, so I am not repeating it here.