title: I've an undirected NetworkX graph and want to find all neighbors of node_a that are also neighbors of node_b
body: <p>Straightforward questions: how do I find all the neighbors in common between node_a and node_b and what's the best way to do it?</p>
  
  <p>The code I have is:</p>
  
  <pre><code>my_node_list_a = [ ... ]
  my_node_list_b = [ ... ]
  
  for c in my_node_list_a:
      for x in nx.neighbors(G, c):
          for y in my_node_list_b:
              for h in nx.neighbors(G, y):
                   if x in y:
                      print(x)
  </code></pre>
  
  <p>This is bad code. First of all I'm having to manually populate <code>my_node_list_a</code> and <code>my_node_list_b</code> by executing <code>for i in G.nodes(): print(i)</code> and only putting in the arrays the nodes I want to run the loop against.</p>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>The title says neighbors, but I'm new to networkx so it might not be the correct term. If neighbors only means the nodes of distance 1 then yes, this is what I want.</p>
  
  <p>However, I'm also interested in what nodes connect the nodes in the arrays <code>my_node_list_a</code> and <code>my_node_list_b</code> that are of greater distance than 1, so if anyone can show me how to do that, it would be useful too (basically, to show me the path(s) between them)</p>
  
  <p><strong>Further edit</strong>:</p>
  
  <p>I need to create a graph from my main graph <code>G</code> based on the neighbors of a selection of nodes.</p>
  
  <p>What is the best way to do that?</p>