Python Forum

Full Version: common element in some lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am wanting a function that does this. i get a list of list (any type sequence of any type sequences). it can even be sets (of course the inner containers must be hashable when the outer container is a set). what i want to find are all things that are in all the inner containers. i could create such a function. but i would like to know if python already has such a thing. if not, is there one in pypy (since the usage of this is for myself). i cannot imagine a name for this to be able to search for it.
Try set.intersection(*others)
and if what i get are not sets?
Convert to set
>>> L = ["caoutchouc", "metro-boulot-dodo", "yaourth", "automobile"]
>>> set.intersection(*(set(x) for x in L))
{'u', 't', 'o'}
Actually, you can convert only the first one to set
>>> set(L[0]).intersection(*L[1:])
{'u', 't', 'o'}
Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> L=[[list,dict,set],[list,str,set],[dict,bool,set]]
>>> set.intersection(*(set(x) for x in L))
{<class 'set'>}
>>> L=[[[],list,dict,set],[list,str,set],[dict,bool,set]]
>>> set.intersection(*(set(x) for x in L))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
TypeError: unhashable type: 'list'
>>>