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
What you are trying to do is almost always a bad idea. Suppose you do get a string containing the name of the list you want. What do you do with it then? There's no nice way to get a variable if all you have is a string containing its name. You can do it with globals()
or locals()
, but those inevitably make your code messy and confusing.
The correct way to do this is to use a list or a dictionary to collect all of the lists you want to search through. Iterating through a single object is much better practice than iterating through every name in the global or local scope.
value = "a"
named_lists = {
"a": ['a','b','c'],
"b": ['d','e','f'],
"d": ['g','h','i'],
"c": ['j','k','l']
}
names = [name for name, seq in named_lists.items() if value in seq]
print(names)
if names: #there may be multiple lists that contain `value`, so let's just look at the first one, if it exists
first_name = names[0]
print(named_lists[first_name])
Result:
['a']
['a', 'b', 'c']