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 isFalse
. 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']
- [Django]-Listen to mqtt topics with django channels and celery
- [Django]-What would be the best way to track Github account activity via their API?
- [Django]-Show children nodes depending on selected parent
- [Django]-Is it possible to use a django filter on the result of a templatetag?
- [Django]-ProgrammingError: when using order_by and distinct together in django