[Django]-IF statement not working with list difference

7πŸ‘

βœ…

In your code example, list3 is indeed empty, since all elements in list1 are in list2 as well.

If you are looking for a list that contains the elements in list1 that are not in list2 and the elements that are in list2 and not in list1, you should use the symmetrical set difference here, this can be performed with the ^ operator, like:

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = list(set(list1) ^ set(list2))

if you are, on the other hand looking for elements in list2 that are not in list1, you should swap the operands:

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = list(set(list2) - set(list1))

If you use - you obtain the set difference [wiki] (or complement) as in:

A βˆ– B = { a∈ A | aβˆ‰ B }

whereas the symmetrical set difference [wiki] (or the disjunctive union) is:

A βŠ• B = (A βˆ– B) βˆͺ (B βˆ– A)

Note: note that the truthiness of a non-empty list is True and that of an empty list is False. You thus should probably rewrite your printing logic to:

if list3:  # not empty
  print(list3)
else: # is empty
  print("None")

2πŸ‘

Here’s another way to do it using in

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = []
for value in list2:
    if value not in list1:
        list3.append(value)

print(list3)

# outputs ['four']
πŸ‘€Axois

Leave a comment