Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if value exists in multiple lists

Tags:

python

list

I have 4 list and each element on the list are unique across the 4 list. How do I find if the value exist in one of the list and return which list it exist?

Example list:

value = 'a'
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']

My expected output is the name of the list where the value is found: For the example above my expected output would be:

a

like image 850
ellaRT Avatar asked Dec 04 '22 01:12

ellaRT


2 Answers

you can use list comprehension:

>>> value ="a"
>>> a = ['a','b','c']
>>> b = ['d','e','f']
>>> d = ['g','h','i']
>>> c = ['j','k','l']
>>> [x for x in a,b,c,d if value in x]
[['a', 'b', 'c']]

To get variable name:

>>> for x in a,b,c,d:
...     if value in x:
...         for key,val in locals().items():
...             if x == val:
...                 print key
...                 break
... 
a

locals() contains local scope variable as dictionary, variable name being key and its value being value

globals contains global scope variable as dictionary, variable name being key and its value being value

like image 80
Hackaholic Avatar answered Dec 06 '22 13:12

Hackaholic


If you don't want to use a list comprehension, you can always use a convoluted and verbose lambda expression!

list(filter(lambda x: value in x, [a,b,c,d]))

EDIT: Question was updated to ask for var name, not var value

like image 39
Tim P Avatar answered Dec 06 '22 13:12

Tim P