Reputation: 35
I'm currently working with NetworkX in Python2 and just faced a weird situation here. I wanted to discover what nodes are connected to each node in a graph, so I wrote this for loop. (I know that each node is only connected to two other nodes, but I need the exact labels)
for i in sorted(graph.nodes(), key=int):
b = [int(edge_tuple[0]) for edge_tuple in PedigNetwork.in_edges(i)]
print i, b
So, for every element i
, b
is a list of length 2, containing the identification of the two nodes that connect to node i
.
But when I try to access the FIRST (b[0]
) element of that list, it returns an error pointing that the index is out of range.
print i, b[0]
IndexError: list index out of range
But if the list has two elements, [0]
is clearly not out of range.
Any ideia how could I solve it? Am I missing something really basic here?
I want to access the first and second elements individually and store them into lists after that.
Thank you very much in advance.
Upvotes: 1
Views: 1156
Reputation: 879421
The error implies b
is the empty list, []
:
In [143]: b = []
In [147]: b[0]
IndexError: list index out of range
That could happen if there is a node i
for which PedigNetwork.in_edges(i)
returns an empty list. To test this theory, you could run
for i in sorted(graph.nodes(), key=int):
b = [int(edge_tuple[0]) for edge_tuple in PedigNetwork.in_edges(i)]
if not b:
print('Empty list: {}, {}'.format(i, b))
break
If it prints Empty list: ...
then you have your culprit.
If you wish to skip nodes where PedigNetwork.in_edges(i)
is empty, you could use
for i in sorted(graph.nodes(), key=int):
b = [int(edge_tuple[0]) for edge_tuple in PedigNetwork.in_edges(i)]
if len(b) < 2: continue
print(i, b[0], b[1])
or
for i in sorted(graph.nodes(), key=int):
b = [int(edge_tuple[0]) for edge_tuple in PedigNetwork.in_edges(i)]
if len(b) >= 2:
print(i, b[0], b[1])
The advantage of using the first option, if len(b) < 2: continue
is that it saves
you one level of indentation.
Upvotes: 2