I have several lists in python, and I would like to take only values which are in each list, is there any function to do it directly?
for example I have:
{'a','b','c','d','e'},{'a','g','c','d','h','e'}, {'i','b','m','d','e','a'}
and I want to make one list which contains
{'a','d','e'}
but i don’t know how many lists I actually have, cause it’s dependent on value ‘i’.
thanks for any help!
if the elements are unique and hashable (and order doesn’t matter in the result), you can use set intersection: e.g.:
This is functionally equivalent to:
The
&operator only works with sets whereas the theintersectionmethod works with any iterable.If you have a list of lists and you want the intersection of all of them, you can do this easily:
special thanks to DSM for pointing this one out
Or you could just use a loop:
Note that if you really want to get the order that they were in the original list, you can do that using a simple sort:
By construction, there is no risk of a
ValueErrorbeing raised here.