Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to find common values in three lists

I try to find common list of values for three different lists:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

of course naturally I try to use the and operator however that way I just get the value of last list in expression:

>> a and b and c
out: [3,4,5,6]

Is any short way to find the common values list:

[3,4]

Br

like image 699
PaulWebbster Avatar asked Jan 21 '15 06:01

PaulWebbster


People also ask

How do you find the common values in three lists in Python?

Algorithm. 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 common items in multiple lists in Python?

We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them .

How do you find common elements in multiple lists?

You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.

How do you find common values in Python?

Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.


1 Answers

Use sets:

>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5]
>>> c = [3, 4, 5, 6]
>>> set(a) & set(b) & set(c)
{3, 4}

Or as Jon suggested:

>>> set(a).intersection(b, c)
{3, 4}

Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the sets, and then the sets are intersected.

The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a, so for longer list, this will be a lot less efficient.

like image 125
poke Avatar answered Sep 22 '22 07:09

poke