Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return the name of a list if it contain the needed value (Python)

am trying to get the name of a list (type list) if it contain the needed value:

def f(Value):
    
    a = ['a','b','c']
    b = ['d','e','f']
    d = ['g','h','i']
    c = ['j','k','l']
    w = next(n for n,v in filter(lambda t: isinstance(t[1],list), locals().items()) if value in v)
    return(w)

f()

well this code will return the name of the list but type string so i will be not able to use it later. thank you in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You got several errors in your code – if you want the list, then return it and not it’s name:

def f(value):                 # capitalization not correct
    
    a = ['a','b','c']
    b = ['d','e','f']
    d = ['g','h','i']
    c = ['j','k','l']

    # set w to v not n - n is the local name, v is the value
    w = next(v for n,v in filter(lambda t: isinstance(t[1],list),
                                 locals().items()) if value in v)

    return w

# needs to be called with parameter
what_list = f("h")

print( what_list )  

Output:

['g', 'h', 'i']

I don’t see the point why using locals().items() in this minimal example, you could do

for li in [a,b,c,d]:  # simply add more lists if needed, no need to inspect locals
    if value in li:
        return li

instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading