Search code examples
pythonlist-comprehension

Creating Two Level List Comprehension in Python


Here's a brain tickler that I have been trying to solve for a couple of hours. The code below takes two lists of integers and returns a list of the items in the 1st list but not the second AND the items in the 2nd list that are not in the first.

def difference(lista, listb):
    output_list = []
    for element in range(len(lista)):
        if lista[element] not in listb:
            output_list.append(lista[element])
    for element in range(len(listb)):
        if listb[element] not in lista:
            output_list.append(listb[element])
    return output_list

list1 = [1, 2, 4, 5, 6]
list2 = [1, 2, 5, 7, 9]

print(f"\nYour lists are {list1} and {list2}, the items in the first, but not in the second.")

The code works, but I am sure there is a way to do this with list comprehension. I have tried:

output_list = [element for element in lista if element not in listb] + [element for element in listb if element not in lista]

This doesn't work. Any clues very gratefully received!


Solution

  • I mean, u can do this in various ways:

    list1 = [1, 2, 4, 5, 6]
    list2 = [1, 2, 5, 7, 9]
    

    using list comprehension:

    [x for x in list1 if x not in list2] + [y for y in list2 if y not in list1]
    

    using python's set + ord:

    list(set(list1) ^ set(list2))
    

    using the python's filter function:

    list(filter(lambda x: x not in list2, list1)) + list(filter(lambda x: x not in list1, list2))
    

    using python's map function:

    from_1 = list(map(lambda x: x if x not in list2 else None, list1))
    from_2 = list(map(lambda x: x if x not in list1 else None, list2))
    output = [x for x in from_1 + from_2 if x is not None]
    

    or even using itertools.chain:

    [item for item in chain(list1, list2) if (item in list1 and item not in list2) or (item in list2 and item not in list1)]