Search code examples
pythonrandomnetworkx

Random node in an Erdos Renyi network


I'm new to networkx, and I want to extract a random node from the erdos_renyi graph, I'm using this code, but I get an empty list

N = 1000 
p = 0.01 
G = nx.erdos_renyi_graph(N, p)
node = list(random.choice(G.nodes()))

Solution

  • You're just a little bit off on your calling sequence:

    node = list(random.choice(G.nodes()))
    

    G.nodes() is a node view of the graph; you need a list of nodes, G.nodes

    node = [ random.choice(list(G.nodes)) ]
    

    Turn the node view into a list, grab a random element form that, and then stuff it into a list (I'm not sure why you wanted a list of one element).