title: Python list comprehension with multiple elements of variable length?
body: <p>I'm writing code to convert a CSV into XML.  Suppose I have a single list like:</p>
  
  <pre><code>input = ['name', 'val', 0, \
           'name', 'val', 1, 'tag', 'val', \
           'name', 'val', 2, 'tag', 'val', 'tag', 'val', \
           'name', 'val', 0]
  </code></pre>
  
  <p>Every slice of this list starting with 'name' denotes an element with a name, a value, and a variable number of optional tag-value pairs.</p>
  
  <p>I want to turn this into:</p>
  
  <pre><code>output = [['name', 'val', []], 
            ['name', 'val', ['tag', 'val']],
            ['name', 'val', ['tag', 'val', 'tag', 'val']],
            ['name', 'val', []]]
  </code></pre>
  
  <p>No need to separate the tag-value pairs into tuples, this is handled in a separate method.  I have a solution, but it's not very pythonic:</p>
  
  <pre><code>output=[]
  cursor=0
  
  while cursor &lt; len(input):
      name=input[cursor]
      val=input[cursor+1]
      ntags=int(input[cursor+2])
      optslice=input[cursor+3:cursor+3+2*ntags]
      cursor = cursor+3+2*ntags
      print name, val, ntags, optslice, cursor
      output.append([name, val, optslice])    
  print output
  
  &gt; name val 0 [] 3
  &gt; name val 1 ['tag', 'val'] 8
  &gt; name val 2 ['tag', 'val', 'tag', 'val'] 15
  &gt; name val 0 [] 18
  
  &gt; [['name', 'val', []], ['name', 'val', ['tag', 'val']], ['name', 'val', ['tag', 'val', 'tag', 'val']], ['name', 'val', []]]
  </code></pre>
  
  <p>I think I could probably do this as a list comprehension, but the variable length of each element is throwing me for a loop.  The input is parsed from a CSV, and I can change the format to better fit a different solution. Ideas?</p>