Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find list intersection?

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?

like image 535
csguy11 Avatar asked Sep 13 '10 01:09

csguy11


People also ask

What is intersection of lists?

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list.

How do you find the intersection of a list in Java?

Intersection of Two Lists of StringsList<String> list = Arrays. asList("red", "blue", "blue", "green", "red"); List<String> otherList = Arrays. asList("red", "green", "green", "yellow");

How do you find the intersection of three lists in Python?

Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.

How do you find the intersection of two sets in Python?

Python count intersection of sets To count the intersection of sets in Python, we will use “len(set(set1) & set(set2))”. Here, ” & “ is an intersection element common to both. It will return the count as “3” because “10, 8, and 6” are common to both the sets.


2 Answers

If order is not important and you don't need to worry about duplicates then you can use set intersection:

>>> a = [1,2,3,4,5] >>> b = [1,3,5,6] >>> list(set(a) & set(b)) [1, 3, 5] 
like image 136
Mark Byers Avatar answered Sep 29 '22 18:09

Mark Byers


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".

like image 29
Lodewijk Avatar answered Sep 29 '22 18:09

Lodewijk