2

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?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Nazhir
  • 87
  • 4
  • how about this ? `for i in list(allNodeCuts): print(i)` – leon gxl Jun 15 '22 at 06:14
  • 3
    `allNodeCuts` is likely a generator - you can get its contents once, but once it is exhausted, you can't get values from it again. Try `for i in a:` – Grismar Jun 15 '22 at 06:16
  • 1
    This question would be a fantastic candidate on why debugging is essential in any programming language. 1 breakpoint and you'd have probably figured out that either that list is empty or (in your case) not a list at all. – JustLudo Jun 15 '22 at 06:16
  • Welcome to Stack Overflow. I [edit]ed the post to fix the code formatting. Please read the [formatting help](https://stackoverflow.com/help/formatting) to understand how to format code properly. – Karl Knechtel Jun 15 '22 at 06:20
  • @JustLudo that would still leave the conceptual question about how generators work. So it would be more clearly a duplicate question, but still a question that needed to be asked. (Also, it was surprisingly difficult for me to find a good duplicate target.) – Karl Knechtel Jun 15 '22 at 06:23
  • @KarlKnechtel: Without going to much offtopic: I agree with that, but it would def. help finding out that what you expect to be a list actually isn't. You don't need knowledge per se on what a generator is. – JustLudo Jun 15 '22 at 09:38

3 Answers3

0

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]
user2314737
  • 27,088
  • 20
  • 102
  • 114
0

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)
leon gxl
  • 75
  • 4
0

I think you should loop a that is:

for i in a:
    print(a)
    
Derek
  • 11
  • 5