Home > Software design >  Return the name of a list if it contain the needed value (Python)
Return the name of a list if it contain the needed value (Python)

Time:04-25

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

CodePudding user response:

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.

  • Related