0

I am trying to check how many neighbours are there in the graph in the networkx object.

neighbours = nxobject.neighbors('Something')
print(len(neighbours))

Error:

TypeError: object of type 'dict_keyiterator' has no len()

It works with print(len(list(neighbours))) but a new problem arises:

print(len(list(neighbours))) 
for child in neighbours: 
  #Do some work 
    return Done_work 
return None 

Now, I'm getting this error:

TypeError: 'NoneType' object is not subscriptable 

1 Answers1

0

An iterator can be used only once. Convert it to a list, then measure the length of the list and/or use that list for further processing:

neighbours = list(nxobject.neighbors('Something'))
print(len(neighbours))
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Need the iterator twice. Can I not make a copy? All I need is to check how many neigbours are there in the loop: If(neighbour <=1): Don't work else Do work – Saiham Rahman Nov 15 '21 at 21:42
  • Once you convert the iterator to a list, you can use that list instead of the iterator. – DYZ Nov 15 '21 at 21:57