title: Unflattening a list in python
body: <p>Problem:</p>
  <blockquote>
  <p>Write a function named &quot;unflatten&quot; which takes a list as an argument
  and constructs a nested list.</p>
  <p>The format of the argument list is as follows:</p>
  <p>An integer item indicates a start of a nested list Non-integer items
  will be the content of the nested list For instance,</p>
  <p><code>[2, 'a', 3, 'b', 'c', 'd']</code> is converted to <code>['a', ['b', 'c', 'd']]</code> The
  first number, 2, indicates that the upper list will contain 2 items.
  <code>'a'</code> is the first item of this upper list. The number 3 indicates a
  start of a new sub-list which contains 3 items.</p>
  </blockquote>
  <p>Sample Run:</p>
  <pre><code>&gt;&gt;&gt; unflatten([2, 'x', 'y'])
  ['x', 'y']
  &gt;&gt;&gt; unflatten([ 3, &quot;a&quot;, &quot;b&quot;, 3, &quot;t&quot;, &quot;y&quot;, &quot;u&quot; ])
  ['a', 'b', ['t', 'y', 'u']]
  &gt;&gt;&gt; unflatten([ 4, &quot;a&quot;, &quot;b&quot;, 3, &quot;c&quot;, &quot;d&quot;, 2, &quot;x&quot;, &quot;y&quot;, 2, &quot;w&quot; , 3, &quot;t&quot;, &quot;y&quot;, &quot;u&quot; ])
  ['a', 'b', ['c', 'd', ['x', 'y']], ['w', ['t', 'y', 'u']]]
  </code></pre>
  <p>I have done a simple recursion. Here is my code:</p>
  <pre><code>def unflatten(LIST):
      if not len(LIST):
         return []
      elif isinstance(LIST[0], int):
          return [unflatten(LIST[1:])]
      else:
          return [LIST[0]]  + unflatten(LIST[1:])
  
  
  &gt;&gt;&gt; unflatten([ 4, &quot;a&quot;, &quot;b&quot;, 3, &quot;c&quot;, &quot;d&quot;, 2, &quot;x&quot;, &quot;y&quot;, 2, &quot;w&quot; , 3, &quot;t&quot;, &quot;y&quot;, &quot;u&quot; ])
  [['a', 'b', ['c', 'd', ['x', 'y', ['w', ['t', 'y', 'u']]]]]]
  </code></pre>
  <p>Now as you can see, lengths of lists are not controlled in my basic recursion, so it simply ends all the lists at the end.</p>
  <p>I don't know how I can track the lengths recursively, or maybe iteratively. I'd be glad if you suggest a way doing this without importing any modules.</p>