Search code examples
pythonpython-3.xlistlambdatypeerror

Python "TypeError: 'list' object is not callable" while calling lambda function


I have this function (reported in a simplified version without many if:

def get_marginals(marginals):
    marginal_dist = []

        if marginals == 'gaussian':
            marginal_dist.append(
                lambda x: scipy.stats.norm.ppf(x)) 
           
        elif marginals == 'student':
            marginal_dist.append(
                lambda x: scipy.stats.t.ppf(x))
  
    return marginal_dist

Now I would like to select the function based on the input:

    mgnl = get_marginals('gaussian')

My expectation is that mgnl is the lambda lambda x: scipy.stats.norm.ppf(x) but unfortunately when I call, for example, mgnl(0.5) I receive the following error:

TypeError: 'list' object is not callable

edit: Please note that marginals can be a list.


Solution

  • def get_marginals(marginals):
        marginal_dist = []
        if marginals == 'gaussian':
            marginal_dist.append(
                lambda x: scipy.stats.norm.ppf(x)) 
        elif marginals == 'student':
            marginal_dist.append(
                lambda x: scipy.stats.t.ppf(x))
        return marginal_dist
    
    mgnl = get_marginals('gaussian')
    

    All your code is good:

    When you call mgnl you will get:

    [<function __main__.get_marginals.<locals>.<lambda>(x)>]
    

    To pass a value you need to take it out of list:

    So, it will be:

    mgnl[0](0.5)