Skipping the print statemnt ! Why?

Viewed 68

I have the following code:

import networkx as nx
G1 = nx.erdos_renyi_graph(10,0.6)
allNodeCuts = nx.all_node_cuts(G1)
a = list(allNodeCuts)

for i in allNodeCuts:
    print(i)

In this version of the code, print(i) does not occur. However, if I move the code a = list(allNodeCuts) after the for loop, the loop runs and elements are printed. Why does this happen?

3 Answers

This is probably because allNodeCuts is a generator and if you list all its elements, you "consume" it (i.e. the pointer is set to the end).

You can see this behavior in the following example:

sq = (x**2 for x in range(3))
type(sq)
# generator
for i in sq:
    print(i)
# 0
# 1
# 4

If you run the loop again the generator is empty:

for i in sq:
    print(i)

To be able to iterate through a generator without losing it one can create a copy with itertools.tee

from itertools import tee

sq, sq_copy = tee(x**2 for x in range(3))
list(sq)
# [0, 1, 4]

# now generator is empty because exhausted
list(sq)
# [] 

# copy is not consumed
list(sq_copy)
# [0, 1, 4]

Have you tried this? Convert the generator to a list, and iterate over the list

import networkx as nx

G1 = nx.erdos_renyi_graph(10,0.6)
allNodeCuts = nx.all_node_cuts(G1)
a = list(allNodeCuts)

for i in a:
    print(i)

I think you should loop a that is:

for i in a:
    print(a)
    
Related