a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c
actual output: [1,3,5,6]
expected output: [1,3,5]
How can we achieve a boolean AND operation (list intersection) on two lists?
a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c
actual output: [1,3,5,6]
expected output: [1,3,5]
How can we achieve a boolean AND operation (list intersection) on two lists?
a = [1,2,3,4,5] b = [1,3,5,6] c = list(set(a).intersection(set(b)))
Should work like a dream. And, if you can, use sets instead of lists to avoid all this type changing!
A functional way can be achieved using
filter
andlambda
operator.Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:
Make a set out of the larger one:
Then,
will do what you want (preserving
b
's ordering, nota
's -- can't necessarily preserve both) and do it fast. (Usingif x in a
as the condition in the list comprehension would also work, and avoid the need to build_auxset
, but unfortunately for lists of substantial length it would be a lot slower).If you want the result to be sorted, rather than preserve either list's ordering, an even neater way might be:
If, by Boolean AND, you mean items that appear in both lists, e.g. intersection, then you should look at Python's
set
andfrozenset
types.Using list comprehensions is a pretty obvious one for me. Not sure about performance, but at least things stay lists.
[x for x in a if x in b]
Or "all the x values that are in A, if the X value is in B".
If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using
intersection()
: