Search code examples
pythonstringlistcontainsexists

How do i check if the elements in a list are contained in other list?


I´m new to Python and I´m having a problem. I have 2 lists containing the names of the columns of a dataset: one has all the columns names (columnas = total.columns.values.tolist()); and the other one has a subset of them ( in the form of "c = [a,b,c,d,c,e,...]".

I would like to know how could I check if each element in "c" is contained in the longer list "columnas". The result i have been trying to get is as it follows ( this is just an example):

a: True b: True c: False ...

Looking forward to your answers, Santiago


Solution

  • You can use what is called a "dictionary-comprehension" to form your result:

    columnas = ['a', 'b', 'z']
    c = ['a', 'b', 'c', 'd', 'c', 'e']
    contained = {x : x in columnas for x in c}
    

    which gives contained as {'a': True, 'b': True, 'c': False, 'd': False, 'e': False}.