title: Insert missing elements in a nested list based on a condition - Python
body: <p>I have the nested list,</p>
  
  <pre><code>a = [(2,0),(3,0),(4,2),(10,3),(11,5)]
  </code></pre>
  
  <p>What I want to do is to add the inner-tuple <code>(0,n)</code> at position <code>n</code>, where <code>n</code> is the location of the missing element in <code>a</code>. The second element in each inner list should increase in increments of one, and if there is a gap then <code>(0,n)</code> should be inserted at that gap.</p>
  
  <p>So the expected outcome for the list <code>a</code> is:</p>
  
  <pre><code>a_out = [(2,0),(3,0),(0,1),(4,2),(10,3),(0,4),(11,5)]
  </code></pre>
  
  <p>I.e since the first and second element in <code>a</code> is <code>(3,0)</code> and <code>(4,2)</code> the so a <code>(0,1)</code> is inserted between them.</p>
  
  <p>My solution works, but I was wondering if there is a more pythonic way of going about it? I have been looking up Python's <a href="http://docs.python.org/2/library/itertools.html" rel="nofollow">itertools</a> library but I can't find a concise solution.</p>
  
  <p>My code so far is:</p>
  
  <pre><code>l1 = [n[1] for n in a]
  l2 = range(max(l1)+1)
  l3 = [n for n in l2 if not in l1]
  
  
  zeros = [0]*len(l3)
  inserts = zip(zeros,l3)
  a_full = a + inserts
  
  a_out = sorted(a_full, key = itemgetter(1))
  </code></pre>
  
  <p>Can anyone suggest a better solution to this??</p>
  
  <p>EDIT:</p>
  
  <p>In general there may be many elements with the same second inner element (for example the <code>(2,0)</code> and <code>(3,0)</code> occuring in <code>a</code>). However, I can group and sum these together without lose of generality.</p>
  
  <p>The nested list <code>a</code> can then be represented as,</p>
  
  <pre><code>a_sum = [(5,0),(4,2),(10,3),(11,5)]
  </code></pre>
  
  <p>By using the code,</p>
  
  <pre><code>a_group = [sum([x for x, y in group]) for key, group in groupby(a, key=itemgetter(1))]
  
  a_sum = zip(output,list(set(l1)))
  </code></pre>
  
  <p>EDIT II:</p>
  
  <p>The length of <code>a</code> is always 600, but depending on how the research goes this may increase to of order 10**3.</p>