rush00121
rush00121

Reputation: 185

python TypeError: 'list' object is not callable error

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

Upvotes: 1

Views: 6621

Answers (3)

Arpan Saini
Arpan Saini

Reputation: 5247

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

Upvotes: 0

Abhijit
Abhijit

Reputation: 63777

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.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 600026

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

Upvotes: 8

Related Questions