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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With