python TypeError: 'list' object is not callable error

Question:

I am novice to python and I am trying to understand a basic error here . I am getting a TypeError: ‘list’ object is not callable error in the below code . Can somebody explain me what is wrong in my code ?

graph = {'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['b', 'd'], 'd': ['a'], 'e': ['a']}


def reachable(graph, node):
    res = [node]
    reachable = graph[node]
    for currentnode in reachable:
        if currentnode not in res :
            reachableNodes = reachable(graph,currentnode) << TypeError: 
            for newNode in reachableNodes:
                if newNode not in res :
                    res.append(newNode)
    return res 

Error : TypeError: ‘list’ object is not callable error

Asked By: rush00121

||

Answers:

You’ve hidden the function name by doing reachable = graph[node]. Use a different name.

Answered By: Daniel Roseman

reachable is your module name which you are calling recursively.

At line 3, when you say reachable = graph[node], it overwrites the variable reachable which was bounded to a function to be now linked to a list (or what ever).

When at line 6, you try to call the function recursively, it ends up trying to call the list which is what reachable is and it fails.

To solve this change the name of the variable, you are intending to hold the list to something different from reachable

canreach = graph[node]
for currentnode in canreach:

Also double check your reachable function. There is a possibility of infinite recursion. Every time you are recursively calling reachable, you are creating a new instance of res. So if currentnode not in res is never false. Try passing res as a parameter, or use it as a global.

Answered By: Abhijit

I restarted the Karnel in JpyterNotebook, and have solved the problem without any change.

Answered By: Arpan Saini
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.