1

I'm using networkx in Python as a functional interface to graph methods and assorted utilities. I want to create a list with all neighbours of a node in a graph.

The webpage states that all_neighbors(graph, node), returns iterator. What does that mean? How do I save the neighbours in a list?

http://networkx.github.io/documentation/latest/reference/generated/networkx.classes.function.all_neighbors.html#networkx.classes.function.all_neighbors

Merni
  • 2,842
  • 5
  • 36
  • 42

2 Answers2

5

Iterators are the new funky jazz in Python, (well not really new) they are basically an object that can be iterated over directly e.g.

for i in all_neighbors(graph, node):
    print i

So when something says it returns an iterator, it means something that can be directly iterated. But is not a list.

To get all the values of an iterator in a list, you can do list(all_neighbors(graph, node))

But just using it directly is far far simpler.

Here is some documentation explaining iterator types.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
1

An iterator is an object that provides values one by one, and does this just once. You can loop over an iterator, or ask for the next value with the next() function, but you cannot index into an iterator (ask for elements in specific locations in the sequence), for example.

You can collect all those values into a list simply by calling list() on the iterator:

list(all_neighbors(graph, node))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343